babylon.solidParticleSystem.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. module BABYLON {
  2. /**
  3. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  4. */
  5. export class SolidParticleSystem implements IDisposable {
  6. // public members
  7. /**
  8. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  9. * Example : var p = SPS.particles[i];
  10. */
  11. public particles: SolidParticle[] = new Array<SolidParticle>();
  12. /**
  13. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  14. */
  15. public nbParticles: number = 0;
  16. /**
  17. * If the particles must ever face the camera (default false). Useful for planar particles.
  18. */
  19. public billboard: boolean = false;
  20. /**
  21. * This a counter ofr your own usage. It's not set by any SPS functions.
  22. */
  23. public counter: number = 0;
  24. /**
  25. * The SPS name. This name is also given to the underlying mesh.
  26. */
  27. public name: string;
  28. /**
  29. * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  30. */
  31. public mesh: Mesh;
  32. /**
  33. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  34. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  35. */
  36. public vars: any = {};
  37. /**
  38. * This array is populated when the SPS is set as 'pickable'.
  39. * Each key of this array is a `faceId` value that you can get from a pickResult object.
  40. * Each element of this array is an object `{idx: int, faceId: int}`.
  41. * `idx` is the picked particle index in the `SPS.particles` array
  42. * `faceId` is the picked face index counted within this particle.
  43. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#pickable-particles
  44. */
  45. public pickedParticles: { idx: number; faceId: number }[];
  46. // private members
  47. private _scene: Scene;
  48. private _positions: number[] = new Array<number>();
  49. private _indices: number[] = new Array<number>();
  50. private _normals: number[] = new Array<number>();
  51. private _colors: number[] = new Array<number>();
  52. private _uvs: number[] = new Array<number>();
  53. private _positions32: Float32Array;
  54. private _normals32: Float32Array; // updated normals for the VBO
  55. private _fixedNormal32: Float32Array; // initial normal references
  56. private _colors32: Float32Array;
  57. private _uvs32: Float32Array;
  58. private _index: number = 0; // indices index
  59. private _updatable: boolean = true;
  60. private _pickable: boolean = false;
  61. private _isVisibilityBoxLocked = false;
  62. private _alwaysVisible: boolean = false;
  63. private _shapeCounter: number = 0;
  64. private _copy: SolidParticle = new SolidParticle(null, null, null, null, null);
  65. private _shape: Vector3[];
  66. private _shapeUV: number[];
  67. private _color: Color4 = new Color4(0, 0, 0, 0);
  68. private _computeParticleColor: boolean = true;
  69. private _computeParticleTexture: boolean = true;
  70. private _computeParticleRotation: boolean = true;
  71. private _computeParticleVertex: boolean = false;
  72. private _computeBoundingBox: boolean = false;
  73. private _cam_axisZ: Vector3 = Vector3.Zero();
  74. private _cam_axisY: Vector3 = Vector3.Zero();
  75. private _cam_axisX: Vector3 = Vector3.Zero();
  76. private _axisX: Vector3 = Axis.X;
  77. private _axisY: Vector3 = Axis.Y;
  78. private _axisZ: Vector3 = Axis.Z;
  79. private _camera: Camera;
  80. private _particle: SolidParticle;
  81. private _fakeCamPos: Vector3 = Vector3.Zero();
  82. private _rotMatrix: Matrix = new Matrix();
  83. private _invertMatrix: Matrix = new Matrix();
  84. private _rotated: Vector3 = Vector3.Zero();
  85. private _quaternion: Quaternion = new Quaternion();
  86. private _vertex: Vector3 = Vector3.Zero();
  87. private _normal: Vector3 = Vector3.Zero();
  88. private _yaw: number = 0.0;
  89. private _pitch: number = 0.0;
  90. private _roll: number = 0.0;
  91. private _halfroll: number = 0.0;
  92. private _halfpitch: number = 0.0;
  93. private _halfyaw: number = 0.0;
  94. private _sinRoll: number = 0.0;
  95. private _cosRoll: number = 0.0;
  96. private _sinPitch: number = 0.0;
  97. private _cosPitch: number = 0.0;
  98. private _sinYaw: number = 0.0;
  99. private _cosYaw: number = 0.0;
  100. private _w: number = 0.0;
  101. private _minimum: Vector3 = Tmp.Vector3[0];
  102. private _maximum: Vector3 = Tmp.Vector3[1];
  103. /**
  104. * Creates a SPS (Solid Particle System) object.
  105. * `name` (String) is the SPS name, this will be the underlying mesh name.
  106. * `scene` (Scene) is the scene in which the SPS is added.
  107. * `updatableè (default true) : if the SPS must be updatable or immutable.
  108. * `isPickable` (default false) : if the solid particles must be pickable.
  109. */
  110. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean }) {
  111. this.name = name;
  112. this._scene = scene;
  113. this._camera = scene.activeCamera;
  114. this._pickable = options ? options.isPickable : false;
  115. if (options && options.updatable) {
  116. this._updatable = options.updatable;
  117. } else {
  118. this._updatable = true;
  119. }
  120. if (this._pickable) {
  121. this.pickedParticles = [];
  122. }
  123. }
  124. /**
  125. * Builds the SPS underlying mesh. Returns a standard Mesh.
  126. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  127. */
  128. public buildMesh(): Mesh {
  129. if (this.nbParticles === 0) {
  130. var triangle = MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  131. this.addShape(triangle, 1);
  132. triangle.dispose();
  133. }
  134. this._positions32 = new Float32Array(this._positions);
  135. this._uvs32 = new Float32Array(this._uvs);
  136. this._colors32 = new Float32Array(this._colors);
  137. VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  138. this._normals32 = new Float32Array(this._normals);
  139. this._fixedNormal32 = new Float32Array(this._normals);
  140. var vertexData = new VertexData();
  141. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  142. vertexData.indices = this._indices;
  143. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  144. if (this._uvs32) {
  145. vertexData.set(this._uvs32, VertexBuffer.UVKind);;
  146. }
  147. if (this._colors32) {
  148. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  149. }
  150. var mesh = new Mesh(this.name, this._scene);
  151. vertexData.applyToMesh(mesh, this._updatable);
  152. this.mesh = mesh;
  153. this.mesh.isPickable = this._pickable;
  154. // free memory
  155. this._positions = null;
  156. this._normals = null;
  157. this._uvs = null;
  158. this._colors = null;
  159. if (!this._updatable) {
  160. this.particles.length = 0;
  161. }
  162. return mesh;
  163. }
  164. /**
  165. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  166. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  167. * Thus the particles generated from `digest()` have their property `position` set yet.
  168. * `mesh` (`Mesh`) is the mesh to be digested
  169. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  170. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  171. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  172. */
  173. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number }): SolidParticleSystem {
  174. var size: number = (options && options.facetNb) || 1;
  175. var number: number = (options && options.number);
  176. var delta: number = (options && options.delta) || 0;
  177. var meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);
  178. var meshInd = mesh.getIndices();
  179. var meshUV = mesh.getVerticesData(VertexBuffer.UVKind);
  180. var meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);
  181. var f: number = 0; // facet counter
  182. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  183. // compute size from number
  184. if (number) {
  185. number = (number > totalFacets) ? totalFacets : number;
  186. size = Math.round(totalFacets / number);
  187. delta = 0;
  188. } else {
  189. size = (size > totalFacets) ? totalFacets : size;
  190. }
  191. var facetPos: number[] = []; // submesh positions
  192. var facetInd: number[] = []; // submesh indices
  193. var facetUV: number[] = []; // submesh UV
  194. var facetCol: number[] = []; // submesh colors
  195. var barycenter: Vector3 = Tmp.Vector3[0];
  196. var rand: number;
  197. var sizeO: number = size;
  198. while (f < totalFacets) {
  199. size = sizeO + Math.floor((1 + delta) * Math.random());
  200. if (f > totalFacets - size) {
  201. size = totalFacets - f;
  202. }
  203. // reset temp arrays
  204. facetPos.length = 0;
  205. facetInd.length = 0;
  206. facetUV.length = 0;
  207. facetCol.length = 0;
  208. // iterate over "size" facets
  209. var fi: number = 0;
  210. for (var j = f * 3; j < (f + size) * 3; j++) {
  211. facetInd.push(fi);
  212. var i: number = meshInd[j];
  213. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  214. if (meshUV) {
  215. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  216. }
  217. if (meshCol) {
  218. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  219. }
  220. fi++;
  221. }
  222. // create a model shape for each single particle
  223. var idx: number = this.nbParticles;
  224. var shape: Vector3[] = this._posToShape(facetPos);
  225. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  226. // compute the barycenter of the shape
  227. var v: number;
  228. for (v = 0; v < shape.length; v++) {
  229. barycenter.addInPlace(shape[v]);
  230. }
  231. barycenter.scaleInPlace(1 / shape.length);
  232. // shift the shape from its barycenter to the origin
  233. for (v = 0; v < shape.length; v++) {
  234. shape[v].subtractInPlace(barycenter);
  235. }
  236. var modelShape = new ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  237. // add the particle in the SPS
  238. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  239. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  240. // initialize the particle position
  241. this.particles[this.nbParticles].position.addInPlace(barycenter);
  242. this._index += shape.length;
  243. idx++;
  244. this.nbParticles++;
  245. this._shapeCounter++;
  246. f += size;
  247. }
  248. return this;
  249. }
  250. //reset copy
  251. private _resetCopy() {
  252. this._copy.position.x = 0;
  253. this._copy.position.y = 0;
  254. this._copy.position.z = 0;
  255. this._copy.rotation.x = 0;
  256. this._copy.rotation.y = 0;
  257. this._copy.rotation.z = 0;
  258. this._copy.rotationQuaternion = null;
  259. this._copy.scaling.x = 1;
  260. this._copy.scaling.y = 1;
  261. this._copy.scaling.z = 1;
  262. this._copy.uvs.x = 0;
  263. this._copy.uvs.y = 0;
  264. this._copy.uvs.z = 1;
  265. this._copy.uvs.w = 1;
  266. this._copy.color = null;
  267. }
  268. // _meshBuilder : inserts the shape model in the global SPS mesh
  269. private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options): void {
  270. var i;
  271. var u = 0;
  272. var c = 0;
  273. this._resetCopy();
  274. if (options && options.positionFunction) { // call to custom positionFunction
  275. options.positionFunction(this._copy, idx, idxInShape);
  276. }
  277. if (this._copy.rotationQuaternion) {
  278. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  279. } else {
  280. this._yaw = this._copy.rotation.y;
  281. this._pitch = this._copy.rotation.x;
  282. this._roll = this._copy.rotation.z;
  283. this._quaternionRotationYPR();
  284. }
  285. this._quaternionToRotationMatrix();
  286. for (i = 0; i < shape.length; i++) {
  287. this._vertex.x = shape[i].x;
  288. this._vertex.y = shape[i].y;
  289. this._vertex.z = shape[i].z;
  290. if (options && options.vertexFunction) {
  291. options.vertexFunction(this._copy, this._vertex, i);
  292. }
  293. this._vertex.x *= this._copy.scaling.x;
  294. this._vertex.y *= this._copy.scaling.y;
  295. this._vertex.z *= this._copy.scaling.z;
  296. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  297. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  298. if (meshUV) {
  299. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  300. u += 2;
  301. }
  302. if (this._copy.color) {
  303. this._color = this._copy.color;
  304. } else if (meshCol && meshCol[c]) {
  305. this._color.r = meshCol[c];
  306. this._color.g = meshCol[c + 1];
  307. this._color.b = meshCol[c + 2];
  308. this._color.a = meshCol[c + 3];
  309. } else {
  310. this._color.r = 1;
  311. this._color.g = 1;
  312. this._color.b = 1;
  313. this._color.a = 1;
  314. }
  315. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  316. c += 4;
  317. }
  318. for (i = 0; i < meshInd.length; i++) {
  319. indices.push(p + meshInd[i]);
  320. }
  321. if (this._pickable) {
  322. var nbfaces = meshInd.length / 3;
  323. for (i = 0; i < nbfaces; i++) {
  324. this.pickedParticles.push({ idx: idx, faceId: i });
  325. }
  326. }
  327. }
  328. // returns a shape array from positions array
  329. private _posToShape(positions): Vector3[] {
  330. var shape = [];
  331. for (var i = 0; i < positions.length; i += 3) {
  332. shape.push(new Vector3(positions[i], positions[i + 1], positions[i + 2]));
  333. }
  334. return shape;
  335. }
  336. // returns a shapeUV array from a Vector4 uvs
  337. private _uvsToShapeUV(uvs): number[] {
  338. var shapeUV = [];
  339. if (uvs) {
  340. for (var i = 0; i < uvs.length; i++)
  341. shapeUV.push(uvs[i]);
  342. }
  343. return shapeUV;
  344. }
  345. // adds a new particle object in the particles array
  346. private _addParticle(idx: number, idxpos: number, model: ModelShape, shapeId: number, idxInShape: number): void {
  347. this.particles.push(new SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  348. }
  349. /**
  350. * Adds some particles to the SPS from the model shape. Returns the shape id.
  351. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  352. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  353. * `nb` (positive integer) the number of particles to be created from this model
  354. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  355. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  356. */
  357. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any }): number {
  358. var meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);
  359. var meshInd = mesh.getIndices();
  360. var meshUV = mesh.getVerticesData(VertexBuffer.UVKind);
  361. var meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);
  362. var shape = this._posToShape(meshPos);
  363. var shapeUV = this._uvsToShapeUV(meshUV);
  364. var posfunc = options ? options.positionFunction : null;
  365. var vtxfunc = options ? options.vertexFunction : null;
  366. var modelShape = new ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  367. // particles
  368. var idx = this.nbParticles;
  369. for (var i = 0; i < nb; i++) {
  370. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  371. if (this._updatable) {
  372. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  373. }
  374. this._index += shape.length;
  375. idx++;
  376. }
  377. this.nbParticles += nb;
  378. this._shapeCounter++;
  379. return this._shapeCounter - 1;
  380. }
  381. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  382. private _rebuildParticle(particle: SolidParticle): void {
  383. this._resetCopy();
  384. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  385. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  386. }
  387. if (this._copy.rotationQuaternion) {
  388. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  389. } else {
  390. this._yaw = this._copy.rotation.y;
  391. this._pitch = this._copy.rotation.x;
  392. this._roll = this._copy.rotation.z;
  393. this._quaternionRotationYPR();
  394. }
  395. this._quaternionToRotationMatrix();
  396. this._shape = particle._model._shape;
  397. for (var pt = 0; pt < this._shape.length; pt++) {
  398. this._vertex.x = this._shape[pt].x;
  399. this._vertex.y = this._shape[pt].y;
  400. this._vertex.z = this._shape[pt].z;
  401. if (particle._model._vertexFunction) {
  402. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  403. }
  404. this._vertex.x *= this._copy.scaling.x;
  405. this._vertex.y *= this._copy.scaling.y;
  406. this._vertex.z *= this._copy.scaling.z;
  407. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  408. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  409. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  410. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  411. }
  412. particle.position.x = 0;
  413. particle.position.y = 0;
  414. particle.position.z = 0;
  415. particle.rotation.x = 0;
  416. particle.rotation.y = 0;
  417. particle.rotation.z = 0;
  418. particle.rotationQuaternion = null;
  419. particle.scaling.x = 1;
  420. particle.scaling.y = 1;
  421. particle.scaling.z = 1;
  422. }
  423. /**
  424. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  425. */
  426. public rebuildMesh(): void {
  427. for (var p = 0; p < this.particles.length; p++) {
  428. this._rebuildParticle(this.particles[p]);
  429. }
  430. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  431. }
  432. /**
  433. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  434. * This method calls `updateParticle()` for each particle of the SPS.
  435. * For an animated SPS, it is usually called within the render loop.
  436. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  437. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  438. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  439. */
  440. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): void {
  441. if (!this._updatable) {
  442. return;
  443. }
  444. // custom beforeUpdate
  445. this.beforeUpdateParticles(start, end, update);
  446. this._cam_axisX.x = 1;
  447. this._cam_axisX.y = 0;
  448. this._cam_axisX.z = 0;
  449. this._cam_axisY.x = 0;
  450. this._cam_axisY.y = 1;
  451. this._cam_axisY.z = 0;
  452. this._cam_axisZ.x = 0;
  453. this._cam_axisZ.y = 0;
  454. this._cam_axisZ.z = 1;
  455. // if the particles will always face the camera
  456. if (this.billboard) {
  457. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  458. this._yaw = this.mesh.rotation.y;
  459. this._pitch = this.mesh.rotation.x;
  460. this._roll = this.mesh.rotation.z;
  461. this._quaternionRotationYPR();
  462. this._quaternionToRotationMatrix();
  463. this._rotMatrix.invertToRef(this._invertMatrix);
  464. Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  465. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  466. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  467. Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  468. Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  469. this._cam_axisY.normalize();
  470. this._cam_axisX.normalize();
  471. this._cam_axisZ.normalize();
  472. }
  473. Matrix.IdentityToRef(this._rotMatrix);
  474. var idx = 0;
  475. var index = 0;
  476. var colidx = 0;
  477. var colorIndex = 0;
  478. var uvidx = 0;
  479. var uvIndex = 0;
  480. if (this._computeBoundingBox) {
  481. Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  482. Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  483. }
  484. // particle loop
  485. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  486. for (var p = start; p <= end; p++) {
  487. this._particle = this.particles[p];
  488. this._shape = this._particle._model._shape;
  489. this._shapeUV = this._particle._model._shapeUV;
  490. // call to custom user function to update the particle properties
  491. this.updateParticle(this._particle);
  492. // particle rotation matrix
  493. if (this.billboard) {
  494. this._particle.rotation.x = 0.0;
  495. this._particle.rotation.y = 0.0;
  496. }
  497. if (this._computeParticleRotation) {
  498. if (this._particle.rotationQuaternion) {
  499. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  500. } else {
  501. this._yaw = this._particle.rotation.y;
  502. this._pitch = this._particle.rotation.x;
  503. this._roll = this._particle.rotation.z;
  504. this._quaternionRotationYPR();
  505. }
  506. this._quaternionToRotationMatrix();
  507. }
  508. for (var pt = 0; pt < this._shape.length; pt++) {
  509. idx = index + pt * 3;
  510. colidx = colorIndex + pt * 4;
  511. uvidx = uvIndex + pt * 2;
  512. this._vertex.x = this._shape[pt].x;
  513. this._vertex.y = this._shape[pt].y;
  514. this._vertex.z = this._shape[pt].z;
  515. if (this._computeParticleVertex) {
  516. this.updateParticleVertex(this._particle, this._vertex, pt);
  517. }
  518. // positions
  519. this._vertex.x *= this._particle.scaling.x;
  520. this._vertex.y *= this._particle.scaling.y;
  521. this._vertex.z *= this._particle.scaling.z;
  522. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  523. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  524. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  525. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  526. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  527. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  528. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  529. if (this._computeBoundingBox) {
  530. if (this._positions32[idx] < this._minimum.x) {
  531. this._minimum.x = this._positions32[idx];
  532. }
  533. if (this._positions32[idx] > this._maximum.x) {
  534. this._maximum.x = this._positions32[idx];
  535. }
  536. if (this._positions32[idx + 1] < this._minimum.y) {
  537. this._minimum.y = this._positions32[idx + 1];
  538. }
  539. if (this._positions32[idx + 1] > this._maximum.y) {
  540. this._maximum.y = this._positions32[idx + 1];
  541. }
  542. if (this._positions32[idx + 2] < this._minimum.z) {
  543. this._minimum.z = this._positions32[idx + 2];
  544. }
  545. if (this._positions32[idx + 2] > this._maximum.z) {
  546. this._maximum.z = this._positions32[idx + 2];
  547. }
  548. }
  549. // normals : if the particles can't be morphed then just rotate the normals
  550. if (!this._computeParticleVertex && !this.billboard) {
  551. this._normal.x = this._fixedNormal32[idx];
  552. this._normal.y = this._fixedNormal32[idx + 1];
  553. this._normal.z = this._fixedNormal32[idx + 2];
  554. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  555. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  556. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  557. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  558. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  559. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  560. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  561. }
  562. if (this._computeParticleColor) {
  563. this._colors32[colidx] = this._particle.color.r;
  564. this._colors32[colidx + 1] = this._particle.color.g;
  565. this._colors32[colidx + 2] = this._particle.color.b;
  566. this._colors32[colidx + 3] = this._particle.color.a;
  567. }
  568. if (this._computeParticleTexture) {
  569. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  570. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  571. }
  572. }
  573. index = idx + 3;
  574. colorIndex = colidx + 4;
  575. uvIndex = uvidx + 2;
  576. }
  577. if (update) {
  578. if (this._computeParticleColor) {
  579. this.mesh.updateVerticesData(VertexBuffer.ColorKind, this._colors32, false, false);
  580. }
  581. if (this._computeParticleTexture) {
  582. this.mesh.updateVerticesData(VertexBuffer.UVKind, this._uvs32, false, false);
  583. }
  584. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  585. if (!this.mesh.areNormalsFrozen) {
  586. if (this._computeParticleVertex || this.billboard) {
  587. // recompute the normals only if the particles can be morphed, update then the normal reference array
  588. VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  589. for (var i = 0; i < this._normals32.length; i++) {
  590. this._fixedNormal32[i] = this._normals32[i];
  591. }
  592. }
  593. this.mesh.updateVerticesData(VertexBuffer.NormalKind, this._normals32, false, false);
  594. }
  595. }
  596. if (this._computeBoundingBox) {
  597. this.mesh._boundingInfo = new BoundingInfo(this._minimum, this._maximum);
  598. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  599. }
  600. this.afterUpdateParticles(start, end, update);
  601. }
  602. private _quaternionRotationYPR(): void {
  603. this._halfroll = this._roll * 0.5;
  604. this._halfpitch = this._pitch * 0.5;
  605. this._halfyaw = this._yaw * 0.5;
  606. this._sinRoll = Math.sin(this._halfroll);
  607. this._cosRoll = Math.cos(this._halfroll);
  608. this._sinPitch = Math.sin(this._halfpitch);
  609. this._cosPitch = Math.cos(this._halfpitch);
  610. this._sinYaw = Math.sin(this._halfyaw);
  611. this._cosYaw = Math.cos(this._halfyaw);
  612. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  613. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  614. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  615. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  616. }
  617. private _quaternionToRotationMatrix(): void {
  618. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  619. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  620. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  621. this._rotMatrix.m[3] = 0;
  622. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  623. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  624. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  625. this._rotMatrix.m[7] = 0;
  626. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  627. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  628. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  629. this._rotMatrix.m[11] = 0;
  630. this._rotMatrix.m[12] = 0;
  631. this._rotMatrix.m[13] = 0;
  632. this._rotMatrix.m[14] = 0;
  633. this._rotMatrix.m[15] = 1.0;
  634. }
  635. /**
  636. * Disposes the SPS
  637. */
  638. public dispose(): void {
  639. this.mesh.dispose();
  640. this.vars = null;
  641. // drop references to internal big arrays for the GC
  642. this._positions = null;
  643. this._indices = null;
  644. this._normals = null;
  645. this._uvs = null;
  646. this._colors = null;
  647. this._positions32 = null;
  648. this._normals32 = null;
  649. this._fixedNormal32 = null;
  650. this._uvs32 = null;
  651. this._colors32 = null;
  652. this.pickedParticles = null;
  653. }
  654. /**
  655. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  656. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  657. */
  658. public refreshVisibleSize(): void {
  659. if (!this._isVisibilityBoxLocked) {
  660. this.mesh.refreshBoundingInfo();
  661. }
  662. }
  663. /**
  664. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  665. * @param size the size (float) of the visibility box
  666. * note : this doesn't lock the SPS mesh bounding box.
  667. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  668. */
  669. public setVisibilityBox(size: number): void {
  670. var vis = size / 2;
  671. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  672. }
  673. // getter and setter
  674. public get isAlwaysVisible(): boolean {
  675. return this._alwaysVisible;
  676. }
  677. /**
  678. * Sets the SPS as always visible or not
  679. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  680. */
  681. public set isAlwaysVisible(val: boolean) {
  682. this._alwaysVisible = val;
  683. this.mesh.alwaysSelectAsActiveMesh = val;
  684. }
  685. /**
  686. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  687. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  688. */
  689. public set isVisibilityBoxLocked(val: boolean) {
  690. this._isVisibilityBoxLocked = val;
  691. this.mesh.getBoundingInfo().isLocked = val;
  692. }
  693. public get isVisibilityBoxLocked(): boolean {
  694. return this._isVisibilityBoxLocked;
  695. }
  696. // Optimizer setters
  697. /**
  698. * Tells to `setParticles()` to compute the particle rotations or not.
  699. * Default value : true. The SPS is faster when it's set to false.
  700. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  701. */
  702. public set computeParticleRotation(val: boolean) {
  703. this._computeParticleRotation = val;
  704. }
  705. /**
  706. * Tells to `setParticles()` to compute the particle colors or not.
  707. * Default value : true. The SPS is faster when it's set to false.
  708. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  709. */
  710. public set computeParticleColor(val: boolean) {
  711. this._computeParticleColor = val;
  712. }
  713. /**
  714. * Tells to `setParticles()` to compute the particle textures or not.
  715. * Default value : true. The SPS is faster when it's set to false.
  716. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  717. */
  718. public set computeParticleTexture(val: boolean) {
  719. this._computeParticleTexture = val;
  720. }
  721. /**
  722. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  723. * Default value : false. The SPS is faster when it's set to false.
  724. * Note : the particle custom vertex positions aren't stored values.
  725. */
  726. public set computeParticleVertex(val: boolean) {
  727. this._computeParticleVertex = val;
  728. }
  729. /**
  730. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  731. */
  732. public set computeBoundingBox(val: boolean) {
  733. this._computeBoundingBox = val;
  734. }
  735. // getters
  736. public get computeParticleRotation(): boolean {
  737. return this._computeParticleRotation;
  738. }
  739. public get computeParticleColor(): boolean {
  740. return this._computeParticleColor;
  741. }
  742. public get computeParticleTexture(): boolean {
  743. return this._computeParticleTexture;
  744. }
  745. public get computeParticleVertex(): boolean {
  746. return this._computeParticleVertex;
  747. }
  748. public get computeBoundingBox(): boolean {
  749. return this._computeBoundingBox;
  750. }
  751. // =======================================================================
  752. // Particle behavior logic
  753. // these following methods may be overwritten by the user to fit his needs
  754. /**
  755. * This function does nothing. It may be overwritten to set all the particle first values.
  756. * The SPS doesn't call this function, you may have to call it by your own.
  757. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  758. */
  759. public initParticles(): void {
  760. }
  761. /**
  762. * This function does nothing. It may be overwritten to recycle a particle.
  763. * The SPS doesn't call this function, you may have to call it by your own.
  764. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  765. */
  766. public recycleParticle(particle: SolidParticle): SolidParticle {
  767. return particle;
  768. }
  769. /**
  770. * Updates a particle : this function should be overwritten by the user.
  771. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  772. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  773. * ex : just set a particle position or velocity and recycle conditions
  774. */
  775. public updateParticle(particle: SolidParticle): SolidParticle {
  776. return particle;
  777. }
  778. /**
  779. * Updates a vertex of a particle : it can be overwritten by the user.
  780. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  781. * @param particle the current particle
  782. * @param vertex the current index of the current particle
  783. * @param pt the index of the current vertex in the particle shape
  784. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  785. * ex : just set a vertex particle position
  786. */
  787. public updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3 {
  788. return vertex;
  789. }
  790. /**
  791. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  792. * This does nothing and may be overwritten by the user.
  793. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  794. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  795. * @param update the boolean update value actually passed to setParticles()
  796. */
  797. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  798. }
  799. /**
  800. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  801. * This will be passed three parameters.
  802. * This does nothing and may be overwritten by the user.
  803. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  804. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  805. * @param update the boolean update value actually passed to setParticles()
  806. */
  807. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  808. }
  809. }
  810. }