solidParticleSystem.ts 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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, SolidParticleVertex } from "./solidParticle";
  11. import { TargetCamera } from "../Cameras/targetCamera";
  12. import { BoundingInfo } from "../Culling/boundingInfo";
  13. import { Axis } from '../Maths/math.axis';
  14. import { SubMesh } from '../Meshes/subMesh';
  15. import { Material } from '../Materials/material';
  16. import { StandardMaterial } from '../Materials/standardMaterial';
  17. import { MultiMaterial } from '../Materials/multiMaterial';
  18. import { PickingInfo } from '../Collisions/pickingInfo';
  19. import { Tools } from '../Misc/tools';
  20. /**
  21. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  22. *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.
  23. * The SPS is also a particle system. It provides some methods to manage the particles.
  24. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  25. *
  26. * Full documentation here : https://doc.babylonjs.com/how_to/Solid_Particle_System
  27. */
  28. export class SolidParticleSystem implements IDisposable {
  29. /**
  30. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  31. * Example : var p = SPS.particles[i];
  32. */
  33. public particles: SolidParticle[] = new Array<SolidParticle>();
  34. /**
  35. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36. */
  37. public nbParticles: number = 0;
  38. /**
  39. * If the particles must ever face the camera (default false). Useful for planar particles.
  40. */
  41. public billboard: boolean = false;
  42. /**
  43. * Recompute normals when adding a shape
  44. */
  45. public recomputeNormals: boolean = false;
  46. /**
  47. * This a counter ofr your own usage. It's not set by any SPS functions.
  48. */
  49. public counter: number = 0;
  50. /**
  51. * The SPS name. This name is also given to the underlying mesh.
  52. */
  53. public name: string;
  54. /**
  55. * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  56. */
  57. public mesh: Mesh;
  58. /**
  59. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60. * Please read : https://doc.babylonjs.com/how_to/Solid_Particle_System#garbage-collector-concerns
  61. */
  62. public vars: any = {};
  63. /**
  64. * This array is populated when the SPS is set as 'pickable'.
  65. * Each key of this array is a `faceId` value that you can get from a pickResult object.
  66. * Each element of this array is an object `{idx: int, faceId: int}`.
  67. * `idx` is the picked particle index in the `SPS.particles` array
  68. * `faceId` is the picked face index counted within this particle.
  69. * This array is the first element of the pickedBySubMesh array : sps.pickBySubMesh[0].
  70. * It's not pertinent to use it when using a SPS with the support for MultiMaterial enabled.
  71. * Use the method SPS.pickedParticle(pickingInfo) instead.
  72. * Please read : https://doc.babylonjs.com/how_to/Solid_Particle_System#pickable-particles
  73. */
  74. public pickedParticles: { idx: number; faceId: number }[];
  75. /**
  76. * This array is populated when the SPS is set as 'pickable'
  77. * Each key of this array is a submesh index.
  78. * Each element of this array is a second array defined like this :
  79. * Each key of this second array is a `faceId` value that you can get from a pickResult object.
  80. * Each element of this second array is an object `{idx: int, faceId: int}`.
  81. * `idx` is the picked particle index in the `SPS.particles` array
  82. * `faceId` is the picked face index counted within this particle.
  83. * It's better to use the method SPS.pickedParticle(pickingInfo) rather than using directly this array.
  84. * Please read : https://doc.babylonjs.com/how_to/Solid_Particle_System#pickable-particles
  85. */
  86. public pickedBySubMesh: { idx: number; faceId: number}[][];
  87. /**
  88. * This array is populated when `enableDepthSort` is set to true.
  89. * Each element of this array is an instance of the class DepthSortedParticle.
  90. */
  91. public depthSortedParticles: DepthSortedParticle[];
  92. /**
  93. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  94. * @hidden
  95. */
  96. public _bSphereOnly: boolean = false;
  97. /**
  98. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  99. * @hidden
  100. */
  101. public _bSphereRadiusFactor: number = 1.0;
  102. private _scene: Scene;
  103. private _positions: number[] = new Array<number>();
  104. private _indices: number[] = new Array<number>();
  105. private _normals: number[] = new Array<number>();
  106. private _colors: number[] = new Array<number>();
  107. private _uvs: number[] = new Array<number>();
  108. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  109. private _positions32: Float32Array; // updated positions for the VBO
  110. private _normals32: Float32Array; // updated normals for the VBO
  111. private _fixedNormal32: Float32Array; // initial normal references
  112. private _colors32: Float32Array;
  113. private _uvs32: Float32Array;
  114. private _index: number = 0; // indices index
  115. private _updatable: boolean = true;
  116. private _pickable: boolean = false;
  117. private _isVisibilityBoxLocked = false;
  118. private _alwaysVisible: boolean = false;
  119. private _depthSort: boolean = false;
  120. private _expandable: boolean = false;
  121. private _shapeCounter: number = 0;
  122. private _copy: SolidParticle = new SolidParticle(0, 0, 0, 0, null, 0, 0, this);
  123. private _color: Color4 = new Color4(0, 0, 0, 0);
  124. private _computeParticleColor: boolean = true;
  125. private _computeParticleTexture: boolean = true;
  126. private _computeParticleRotation: boolean = true;
  127. private _computeParticleVertex: boolean = false;
  128. private _computeBoundingBox: boolean = false;
  129. private _depthSortParticles: boolean = true;
  130. private _camera: TargetCamera;
  131. private _mustUnrotateFixedNormals = false;
  132. private _particlesIntersect: boolean = false;
  133. private _needs32Bits: boolean = false;
  134. private _isNotBuilt: boolean = true;
  135. private _lastParticleId: number = 0;
  136. private _idxOfId: number[] = []; // array : key = particle.id / value = particle.idx
  137. private _multimaterialEnabled: boolean = false;
  138. private _useModelMaterial: boolean = false;
  139. private _indicesByMaterial: number[];
  140. private _materialIndexes: number[];
  141. private _depthSortFunction = (p1: DepthSortedParticle, p2: DepthSortedParticle) => p2.sqDistance - p1.sqDistance;
  142. private _materialSortFunction = (p1: DepthSortedParticle, p2: DepthSortedParticle) => p1.materialIndex - p2.materialIndex;
  143. private _materials: Material[];
  144. private _multimaterial: MultiMaterial;
  145. private _materialIndexesById: any;
  146. private _defaultMaterial: Material;
  147. private _autoUpdateSubMeshes: boolean = false;
  148. private _tmpVertex: SolidParticleVertex;
  149. /**
  150. * Creates a SPS (Solid Particle System) object.
  151. * @param name (String) is the SPS name, this will be the underlying mesh name.
  152. * @param scene (Scene) is the scene in which the SPS is added.
  153. * @param options defines the options of the sps e.g.
  154. * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  155. * * isPickable (optional boolean, default false) : if the solid particles must be pickable.
  156. * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  157. * * useModelMaterial (optional boolean, defaut false) : if the model materials must be used to create the SPS multimaterial. This enables the multimaterial supports of the SPS.
  158. * * enableMultiMaterial (optional boolean, default false) : if the solid particles can be given different materials.
  159. * * expandable (optional boolean, default false) : if particles can still be added after the initial SPS mesh creation.
  160. * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  161. * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  162. * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  163. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  164. */
  165. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean; enableDepthSort?: boolean; particleIntersection?: boolean; boundingSphereOnly?: boolean; bSphereRadiusFactor?: number; expandable?: boolean; useModelMaterial?: boolean; enableMultiMaterial?: boolean; }) {
  166. this.name = name;
  167. this._scene = scene || EngineStore.LastCreatedScene;
  168. this._camera = <TargetCamera>scene.activeCamera;
  169. this._pickable = options ? <boolean>options.isPickable : false;
  170. this._depthSort = options ? <boolean>options.enableDepthSort : false;
  171. this._multimaterialEnabled = options ? <boolean>options.enableMultiMaterial : false;
  172. this._useModelMaterial = options ? <boolean>options.useModelMaterial : false;
  173. this._multimaterialEnabled = (this._useModelMaterial) ? true : this._multimaterialEnabled;
  174. this._expandable = options ? <boolean>options.expandable : false;
  175. this._particlesIntersect = options ? <boolean>options.particleIntersection : false;
  176. this._bSphereOnly = options ? <boolean>options.boundingSphereOnly : false;
  177. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  178. if (options && options.updatable !== undefined) {
  179. this._updatable = options.updatable;
  180. } else {
  181. this._updatable = true;
  182. }
  183. if (this._pickable) {
  184. this.pickedBySubMesh = [[]];
  185. this.pickedParticles = this.pickedBySubMesh[0];
  186. }
  187. if (this._depthSort || this._multimaterialEnabled) {
  188. this.depthSortedParticles = [];
  189. }
  190. if (this._multimaterialEnabled) {
  191. this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene);
  192. this._materials = [];
  193. this._materialIndexesById = {};
  194. }
  195. this._tmpVertex = new SolidParticleVertex();
  196. }
  197. /**
  198. * Builds the SPS underlying mesh. Returns a standard Mesh.
  199. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  200. * @returns the created mesh
  201. */
  202. public buildMesh(): Mesh {
  203. if (!this._isNotBuilt && this.mesh) {
  204. return this.mesh;
  205. }
  206. if (this.nbParticles === 0 && !this.mesh) {
  207. var triangle = DiscBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  208. this.addShape(triangle, 1);
  209. triangle.dispose();
  210. }
  211. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  212. this._positions32 = new Float32Array(this._positions);
  213. this._uvs32 = new Float32Array(this._uvs);
  214. this._colors32 = new Float32Array(this._colors);
  215. if (!this.mesh) { // in case it's already expanded
  216. var mesh = new Mesh(this.name, this._scene);
  217. this.mesh = mesh;
  218. }
  219. if (!this._updatable && this._multimaterialEnabled) {
  220. this._sortParticlesByMaterial(); // this may reorder the indices32
  221. }
  222. if (this.recomputeNormals) {
  223. VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  224. }
  225. this._normals32 = new Float32Array(this._normals);
  226. this._fixedNormal32 = new Float32Array(this._normals);
  227. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  228. this._unrotateFixedNormals();
  229. }
  230. var vertexData = new VertexData();
  231. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  232. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  233. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  234. if (this._uvs32.length > 0) {
  235. vertexData.set(this._uvs32, VertexBuffer.UVKind);
  236. }
  237. if (this._colors32.length > 0) {
  238. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  239. }
  240. vertexData.applyToMesh(this.mesh, this._updatable);
  241. this.mesh.isPickable = this._pickable;
  242. if (this._pickable) {
  243. let faceId = 0;
  244. for (let p = 0; p < this.nbParticles; p++) {
  245. let part = this.particles[p];
  246. let lind = part._model._indicesLength;
  247. for (let i = 0; i < lind; i++) {
  248. let f = i % 3;
  249. if (f == 0) {
  250. const pickedData = {idx: part.idx, faceId: faceId};
  251. this.pickedParticles[faceId] = pickedData;
  252. faceId++;
  253. }
  254. }
  255. }
  256. }
  257. if (this._multimaterialEnabled) {
  258. this.setMultiMaterial(this._materials);
  259. }
  260. if (!this._expandable) {
  261. // free memory
  262. if (!this._depthSort && !this._multimaterialEnabled) {
  263. (<any>this._indices) = null;
  264. }
  265. (<any>this._positions) = null;
  266. (<any>this._normals) = null;
  267. (<any>this._uvs) = null;
  268. (<any>this._colors) = null;
  269. if (!this._updatable) {
  270. this.particles.length = 0;
  271. }
  272. }
  273. this._isNotBuilt = false;
  274. this.recomputeNormals = false;
  275. return this.mesh;
  276. }
  277. /**
  278. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  279. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  280. * Thus the particles generated from `digest()` have their property `position` set yet.
  281. * @param mesh ( Mesh ) is the mesh to be digested
  282. * @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
  283. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  284. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  285. * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.
  286. * @returns the current SPS
  287. */
  288. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number; storage?: [] }): SolidParticleSystem {
  289. var size: number = (options && options.facetNb) || 1;
  290. var number: number = (options && options.number) || 0;
  291. var delta: number = (options && options.delta) || 0;
  292. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  293. var meshInd = <IndicesArray>mesh.getIndices();
  294. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  295. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  296. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  297. var storage = (options && options.storage) ? options.storage : null;
  298. var f: number = 0; // facet counter
  299. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  300. // compute size from number
  301. if (number) {
  302. number = (number > totalFacets) ? totalFacets : number;
  303. size = Math.round(totalFacets / number);
  304. delta = 0;
  305. } else {
  306. size = (size > totalFacets) ? totalFacets : size;
  307. }
  308. var facetPos: number[] = []; // submesh positions
  309. var facetNor: number[] = [];
  310. var facetInd: number[] = []; // submesh indices
  311. var facetUV: number[] = []; // submesh UV
  312. var facetCol: number[] = []; // submesh colors
  313. var barycenter: Vector3 = Vector3.Zero();
  314. var sizeO: number = size;
  315. while (f < totalFacets) {
  316. size = sizeO + Math.floor((1 + delta) * Math.random());
  317. if (f > totalFacets - size) {
  318. size = totalFacets - f;
  319. }
  320. // reset temp arrays
  321. facetPos.length = 0;
  322. facetNor.length = 0;
  323. facetInd.length = 0;
  324. facetUV.length = 0;
  325. facetCol.length = 0;
  326. // iterate over "size" facets
  327. var fi: number = 0;
  328. for (var j = f * 3; j < (f + size) * 3; j++) {
  329. facetInd.push(fi);
  330. var i: number = meshInd[j];
  331. var i3: number = i * 3;
  332. facetPos.push(meshPos[i3], meshPos[i3 + 1], meshPos[i3 + 2]);
  333. facetNor.push(meshNor[i3], meshNor[i3 + 1], meshNor[i3 + 2]);
  334. if (meshUV) {
  335. var i2: number = i * 2;
  336. facetUV.push(meshUV[i2], meshUV[i2 + 1]);
  337. }
  338. if (meshCol) {
  339. var i4: number = i * 4;
  340. facetCol.push(meshCol[i4], meshCol[i4 + 1], meshCol[i4 + 2], meshCol[i4 + 3]);
  341. }
  342. fi++;
  343. }
  344. // create a model shape for each single particle
  345. var idx: number = this.nbParticles;
  346. var shape: Vector3[] = this._posToShape(facetPos);
  347. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  348. var shapeInd = Tools.Slice(facetInd);
  349. var shapeCol = Tools.Slice(facetCol);
  350. var shapeNor = Tools.Slice(facetNor);
  351. // compute the barycenter of the shape
  352. barycenter.copyFromFloats(0, 0, 0);
  353. var v: number;
  354. for (v = 0; v < shape.length; v++) {
  355. barycenter.addInPlace(shape[v]);
  356. }
  357. barycenter.scaleInPlace(1 / shape.length);
  358. // shift the shape from its barycenter to the origin
  359. // and compute the BBox required for intersection.
  360. var minimum: Vector3 = new Vector3(Infinity, Infinity, Infinity);
  361. var maximum: Vector3 = new Vector3(-Infinity, -Infinity, -Infinity);
  362. for (v = 0; v < shape.length; v++) {
  363. shape[v].subtractInPlace(barycenter);
  364. minimum.minimizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);
  365. maximum.maximizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);
  366. }
  367. var bInfo;
  368. if (this._particlesIntersect) {
  369. bInfo = new BoundingInfo(minimum, maximum);
  370. }
  371. var material = null;
  372. if (this._useModelMaterial) {
  373. material = (mesh.material) ? mesh.material : this._setDefaultMaterial();
  374. }
  375. var modelShape = new ModelShape(this._shapeCounter, shape, shapeInd, shapeNor, shapeCol, shapeUV, null, null, material);
  376. // add the particle in the SPS
  377. var currentPos = this._positions.length;
  378. var currentInd = this._indices.length;
  379. this._meshBuilder(this._index, currentInd, shape, this._positions, shapeInd, this._indices, facetUV, this._uvs, shapeCol, this._colors, shapeNor, this._normals, idx, 0, null, modelShape);
  380. this._addParticle(idx, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo, storage);
  381. // initialize the particle position
  382. this.particles[this.nbParticles].position.addInPlace(barycenter);
  383. if (!storage) {
  384. this._index += shape.length;
  385. idx++;
  386. this.nbParticles++;
  387. this._lastParticleId++;
  388. }
  389. this._shapeCounter++;
  390. f += size;
  391. }
  392. this._isNotBuilt = true; // buildMesh() is now expected for setParticles() to work
  393. return this;
  394. }
  395. /**
  396. * Unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  397. * @hidden
  398. */
  399. private _unrotateFixedNormals() {
  400. var index = 0;
  401. var idx = 0;
  402. const tmpNormal = TmpVectors.Vector3[0];
  403. const quaternion = TmpVectors.Quaternion[0];
  404. const invertedRotMatrix = TmpVectors.Matrix[0];
  405. for (var p = 0; p < this.particles.length; p++) {
  406. const particle = this.particles[p];
  407. const shape = particle._model._shape;
  408. // computing the inverse of the rotation matrix from the quaternion
  409. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  410. if (particle.rotationQuaternion) {
  411. particle.rotationQuaternion.conjugateToRef(quaternion);
  412. }
  413. else {
  414. const rotation = particle.rotation;
  415. Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  416. quaternion.conjugateInPlace();
  417. }
  418. quaternion.toRotationMatrix(invertedRotMatrix);
  419. for (var pt = 0; pt < shape.length; pt++) {
  420. idx = index + pt * 3;
  421. Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  422. tmpNormal.toArray(this._fixedNormal32, idx);
  423. }
  424. index = idx + 3;
  425. }
  426. }
  427. /**
  428. * Resets the temporary working copy particle
  429. * @hidden
  430. */
  431. private _resetCopy() {
  432. const copy = this._copy;
  433. copy.position.setAll(0);
  434. copy.rotation.setAll(0);
  435. copy.rotationQuaternion = null;
  436. copy.scaling.setAll(1);
  437. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  438. copy.color = null;
  439. copy.translateFromPivot = false;
  440. copy.shapeId = 0;
  441. copy.materialIndex = null;
  442. }
  443. /**
  444. * Inserts the shape model geometry in the global SPS mesh by updating the positions, indices, normals, colors, uvs arrays
  445. * @param p the current index in the positions array to be updated
  446. * @param ind the current index in the indices array
  447. * @param shape a Vector3 array, the shape geometry
  448. * @param positions the positions array to be updated
  449. * @param meshInd the shape indices array
  450. * @param indices the indices array to be updated
  451. * @param meshUV the shape uv array
  452. * @param uvs the uv array to be updated
  453. * @param meshCol the shape color array
  454. * @param colors the color array to be updated
  455. * @param meshNor the shape normals array
  456. * @param normals the normals array to be updated
  457. * @param idx the particle index
  458. * @param idxInShape the particle index in its shape
  459. * @param options the addShape() method passed options
  460. * @model the particle model
  461. * @hidden
  462. */
  463. private _meshBuilder(p: number, ind: 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, model: ModelShape): SolidParticle {
  464. var i;
  465. var u = 0;
  466. var c = 0;
  467. var n = 0;
  468. this._resetCopy();
  469. const copy = this._copy;
  470. const storeApart = (options && options.storage) ? true : false;
  471. copy.idx = idx;
  472. copy.idxInShape = idxInShape;
  473. copy.shapeId = model.shapeID;
  474. if (this._useModelMaterial) {
  475. var materialId = model._material!.uniqueId;
  476. const materialIndexesById = this._materialIndexesById;
  477. if (!materialIndexesById.hasOwnProperty(materialId)) {
  478. materialIndexesById[materialId] = this._materials.length;
  479. this._materials.push(model._material!);
  480. }
  481. var matIdx = materialIndexesById[materialId];
  482. copy.materialIndex = matIdx;
  483. }
  484. if (options && options.positionFunction) { // call to custom positionFunction
  485. options.positionFunction(copy, idx, idxInShape);
  486. this._mustUnrotateFixedNormals = true;
  487. }
  488. // in case the particle geometry must NOT be inserted in the SPS mesh geometry
  489. if (storeApart) {
  490. return copy;
  491. }
  492. const rotMatrix = TmpVectors.Matrix[0];
  493. const tmpVertex = this._tmpVertex;
  494. const tmpVector = tmpVertex.position;
  495. const tmpColor = tmpVertex.color;
  496. const tmpUV = tmpVertex.uv;
  497. const tmpRotated = TmpVectors.Vector3[1];
  498. const pivotBackTranslation = TmpVectors.Vector3[2];
  499. const scaledPivot = TmpVectors.Vector3[3];
  500. Matrix.IdentityToRef(rotMatrix);
  501. copy.getRotationMatrix(rotMatrix);
  502. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  503. if (copy.translateFromPivot) {
  504. pivotBackTranslation.setAll(0.0);
  505. }
  506. else {
  507. pivotBackTranslation.copyFrom(scaledPivot);
  508. }
  509. var someVertexFunction = (options && options.vertexFunction);
  510. for (i = 0; i < shape.length; i++) {
  511. tmpVector.copyFrom(shape[i]);
  512. if (copy.color) {
  513. tmpColor.copyFrom(copy.color);
  514. }
  515. if (meshUV) {
  516. tmpUV.copyFromFloats(meshUV[u], meshUV[u + 1]);
  517. }
  518. if (someVertexFunction) {
  519. options.vertexFunction(copy, tmpVertex, i);
  520. }
  521. tmpVector.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  522. Vector3.TransformCoordinatesToRef(tmpVector, rotMatrix, tmpRotated);
  523. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  524. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  525. if (meshUV) {
  526. const copyUvs = copy.uvs;
  527. uvs.push((copyUvs.z - copyUvs.x) * tmpUV.x + copyUvs.x, (copyUvs.w - copyUvs.y) * tmpUV.y + copyUvs.y);
  528. u += 2;
  529. }
  530. if (copy.color) {
  531. this._color.copyFrom(tmpColor);
  532. } else {
  533. const color = this._color;
  534. if (meshCol && meshCol[c] !== undefined) {
  535. color.r = meshCol[c];
  536. color.g = meshCol[c + 1];
  537. color.b = meshCol[c + 2];
  538. color.a = meshCol[c + 3];
  539. } else {
  540. color.r = 1.0;
  541. color.g = 1.0;
  542. color.b = 1.0;
  543. color.a = 1.0;
  544. }
  545. }
  546. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  547. c += 4;
  548. if (!this.recomputeNormals && meshNor) {
  549. Vector3.TransformNormalFromFloatsToRef(meshNor[n], meshNor[n + 1], meshNor[n + 2], rotMatrix, tmpVector);
  550. normals.push(tmpVector.x, tmpVector.y, tmpVector.z);
  551. n += 3;
  552. }
  553. }
  554. for (i = 0; i < meshInd.length; i++) {
  555. var current_ind = p + meshInd[i];
  556. indices.push(current_ind);
  557. if (current_ind > 65535) {
  558. this._needs32Bits = true;
  559. }
  560. }
  561. if (this._depthSort || this._multimaterialEnabled) {
  562. var matIndex = (copy.materialIndex !== null) ? copy.materialIndex : 0;
  563. this.depthSortedParticles.push(new DepthSortedParticle(idx, ind, meshInd.length, matIndex));
  564. }
  565. return copy;
  566. }
  567. /**
  568. * Returns a shape Vector3 array from positions float array
  569. * @param positions float array
  570. * @returns a vector3 array
  571. * @hidden
  572. */
  573. private _posToShape(positions: number[] | Float32Array): Vector3[] {
  574. var shape = [];
  575. for (var i = 0; i < positions.length; i += 3) {
  576. shape.push(Vector3.FromArray(positions, i));
  577. }
  578. return shape;
  579. }
  580. /**
  581. * Returns a shapeUV array from a float uvs (array deep copy)
  582. * @param uvs as a float array
  583. * @returns a shapeUV array
  584. * @hidden
  585. */
  586. private _uvsToShapeUV(uvs: number[] | Float32Array): number[] {
  587. var shapeUV = [];
  588. if (uvs) {
  589. for (var i = 0; i < uvs.length; i++) {
  590. shapeUV.push(uvs[i]);
  591. }
  592. }
  593. return shapeUV;
  594. }
  595. /**
  596. * Adds a new particle object in the particles array
  597. * @param idx particle index in particles array
  598. * @param id particle id
  599. * @param idxpos positionIndex : the starting index of the particle vertices in the SPS "positions" array
  600. * @param idxind indiceIndex : he starting index of the particle indices in the SPS "indices" array
  601. * @param model particle ModelShape object
  602. * @param shapeId model shape identifier
  603. * @param idxInShape index of the particle in the current model
  604. * @param bInfo model bounding info object
  605. * @param storage target storage array, if any
  606. * @hidden
  607. */
  608. private _addParticle(idx: number, id: number, idxpos: number, idxind: number, model: ModelShape, shapeId: number, idxInShape: number, bInfo: Nullable<BoundingInfo> = null, storage: Nullable<[]> = null): SolidParticle {
  609. var sp = new SolidParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  610. var target = (storage) ? storage : this.particles;
  611. target.push(sp);
  612. return sp;
  613. }
  614. /**
  615. * Adds some particles to the SPS from the model shape. Returns the shape id.
  616. * Please read the doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#create-an-immutable-sps
  617. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  618. * @param nb (positive integer) the number of particles to be created from this model
  619. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  620. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  621. * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.
  622. * @returns the number of shapes in the system
  623. */
  624. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any; storage?: [] }): number {
  625. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  626. var meshInd = <IndicesArray>mesh.getIndices();
  627. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  628. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  629. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  630. this.recomputeNormals = (meshNor) ? false : true;
  631. var indices = Tools.SliceToArray<IndicesArray, number>(meshInd);
  632. var shapeNormals = Tools.SliceToArray<number[] | Float32Array, number>(meshNor);
  633. var shapeColors = (meshCol) ? Tools.SliceToArray<number[] | Float32Array, number>(meshCol) : [];
  634. var storage = (options && options.storage) ? options.storage : null;
  635. var bbInfo: Nullable<BoundingInfo> = null;
  636. if (this._particlesIntersect) {
  637. bbInfo = mesh.getBoundingInfo();
  638. }
  639. var shape = this._posToShape(meshPos);
  640. var shapeUV = this._uvsToShapeUV(meshUV);
  641. var posfunc = options ? options.positionFunction : null;
  642. var vtxfunc = options ? options.vertexFunction : null;
  643. var material = null;
  644. if (this._useModelMaterial) {
  645. material = (mesh.material) ? mesh.material : this._setDefaultMaterial();
  646. }
  647. var modelShape = new ModelShape(this._shapeCounter, shape, indices, shapeNormals, shapeColors, shapeUV, posfunc, vtxfunc, material);
  648. // particles
  649. for (var i = 0; i < nb; i++) {
  650. this._insertNewParticle(this.nbParticles, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options);
  651. }
  652. this._shapeCounter++;
  653. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  654. return this._shapeCounter - 1;
  655. }
  656. /**
  657. * Rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  658. * @hidden
  659. */
  660. private _rebuildParticle(particle: SolidParticle, reset: boolean = false): void {
  661. this._resetCopy();
  662. const copy = this._copy;
  663. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  664. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  665. }
  666. const rotMatrix = TmpVectors.Matrix[0];
  667. const tmpVertex = TmpVectors.Vector3[0];
  668. const tmpRotated = TmpVectors.Vector3[1];
  669. const pivotBackTranslation = TmpVectors.Vector3[2];
  670. const scaledPivot = TmpVectors.Vector3[3];
  671. copy.getRotationMatrix(rotMatrix);
  672. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  673. if (copy.translateFromPivot) {
  674. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  675. }
  676. else {
  677. pivotBackTranslation.copyFrom(scaledPivot);
  678. }
  679. const shape = particle._model._shape;
  680. for (var pt = 0; pt < shape.length; pt++) {
  681. tmpVertex.copyFrom(shape[pt]);
  682. if (particle._model._vertexFunction) {
  683. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  684. }
  685. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  686. Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  687. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  688. }
  689. if (reset) {
  690. particle.position.setAll(0.0);
  691. particle.rotation.setAll(0.0);
  692. particle.rotationQuaternion = null;
  693. particle.scaling.setAll(1.0);
  694. particle.uvs.setAll(0.0);
  695. particle.pivot.setAll(0.0);
  696. particle.translateFromPivot = false;
  697. particle.parentId = null;
  698. }
  699. }
  700. /**
  701. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  702. * @param reset boolean, default false : if the particles must be reset at position and rotation zero, scaling 1, color white, initial UVs and not parented.
  703. * @returns the SPS.
  704. */
  705. public rebuildMesh(reset: boolean = false): SolidParticleSystem {
  706. for (var p = 0; p < this.particles.length; p++) {
  707. this._rebuildParticle(this.particles[p], reset);
  708. }
  709. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  710. return this;
  711. }
  712. /** Removes the particles from the start-th to the end-th included from an expandable SPS (required).
  713. * Returns an array with the removed particles.
  714. * If the number of particles to remove is lower than zero or greater than the global remaining particle number, then an empty array is returned.
  715. * The SPS can't be empty so at least one particle needs to remain in place.
  716. * Under the hood, the VertexData array, so the VBO buffer, is recreated each call.
  717. * @param start index of the first particle to remove
  718. * @param end index of the last particle to remove (included)
  719. * @returns an array populated with the removed particles
  720. */
  721. public removeParticles(start: number, end: number): SolidParticle[] {
  722. var nb = end - start + 1;
  723. if (!this._expandable || nb <= 0 || nb >= this.nbParticles || !this._updatable) {
  724. return [];
  725. }
  726. const particles = this.particles;
  727. const currentNb = this.nbParticles;
  728. if (end < currentNb - 1) { // update the particle indexes in the positions array in case they're remaining particles after the last removed
  729. var firstRemaining = end + 1;
  730. var shiftPos = particles[firstRemaining]._pos - particles[start]._pos;
  731. var shifInd = particles[firstRemaining]._ind - particles[start]._ind;
  732. for (var i = firstRemaining; i < currentNb; i++) {
  733. var part = particles[i];
  734. part._pos -= shiftPos;
  735. part._ind -= shifInd;
  736. }
  737. }
  738. var removed = particles.splice(start, nb);
  739. this._positions.length = 0;
  740. this._indices.length = 0;
  741. this._colors.length = 0;
  742. this._uvs.length = 0;
  743. this._normals.length = 0;
  744. this._index = 0;
  745. this._idxOfId.length = 0;
  746. if (this._depthSort || this._multimaterialEnabled) {
  747. this.depthSortedParticles = [];
  748. }
  749. var ind = 0;
  750. const particlesLength = particles.length;
  751. for (var p = 0; p < particlesLength; p++) {
  752. var particle = particles[p];
  753. var model = particle._model;
  754. var shape = model._shape;
  755. var modelIndices = model._indices;
  756. var modelNormals = model._normals;
  757. var modelColors = model._shapeColors;
  758. var modelUVs = model._shapeUV;
  759. particle.idx = p;
  760. this._idxOfId[particle.id] = p;
  761. this._meshBuilder(this._index, ind, shape, this._positions, modelIndices, this._indices, modelUVs, this._uvs, modelColors, this._colors, modelNormals, this._normals, particle.idx, particle.idxInShape, null, model);
  762. this._index += shape.length;
  763. ind += modelIndices.length;
  764. }
  765. this.nbParticles -= nb;
  766. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  767. return removed;
  768. }
  769. /**
  770. * Inserts some pre-created particles in the solid particle system so that they can be managed by setParticles().
  771. * @param solidParticleArray an array populated with Solid Particles objects
  772. * @returns the SPS
  773. */
  774. public insertParticlesFromArray(solidParticleArray: SolidParticle[]): SolidParticleSystem {
  775. if (!this._expandable) {
  776. return this;
  777. }
  778. var idxInShape = 0;
  779. var currentShapeId = solidParticleArray[0].shapeId;
  780. const nb = solidParticleArray.length;
  781. for (var i = 0; i < nb; i++) {
  782. var sp = solidParticleArray[i];
  783. var model = sp._model;
  784. var shape = model._shape;
  785. var meshInd = model._indices;
  786. var meshUV = model._shapeUV;
  787. var meshCol = model._shapeColors;
  788. var meshNor = model._normals;
  789. var noNor = (meshNor) ? false : true;
  790. this.recomputeNormals = (noNor || this.recomputeNormals);
  791. var bbInfo = sp._boundingInfo;
  792. var newPart = this._insertNewParticle(this.nbParticles, idxInShape, model, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, null, null);
  793. sp.copyToRef(newPart!);
  794. idxInShape++;
  795. if (currentShapeId != sp.shapeId) {
  796. currentShapeId = sp.shapeId;
  797. idxInShape = 0;
  798. }
  799. }
  800. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  801. return this;
  802. }
  803. /**
  804. * Creates a new particle and modifies the SPS mesh geometry :
  805. * - calls _meshBuilder() to increase the SPS mesh geometry step by step
  806. * - calls _addParticle() to populate the particle array
  807. * factorized code from addShape() and insertParticlesFromArray()
  808. * @param idx particle index in the particles array
  809. * @param i particle index in its shape
  810. * @param modelShape particle ModelShape object
  811. * @param shape shape vertex array
  812. * @param meshInd shape indices array
  813. * @param meshUV shape uv array
  814. * @param meshCol shape color array
  815. * @param meshNor shape normals array
  816. * @param bbInfo shape bounding info
  817. * @param storage target particle storage
  818. * @options addShape() passed options
  819. * @hidden
  820. */
  821. private _insertNewParticle(idx: number, i: number, modelShape: ModelShape, shape: Vector3[], meshInd: IndicesArray, meshUV: number[] | Float32Array, meshCol: number[] | Float32Array, meshNor: number[] | Float32Array, bbInfo: Nullable<BoundingInfo>, storage: Nullable<[]> , options: any): Nullable<SolidParticle> {
  822. var currentPos = this._positions.length;
  823. var currentInd = this._indices.length;
  824. var currentCopy = this._meshBuilder(this._index, currentInd, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options, modelShape);
  825. var sp: Nullable<SolidParticle> = null;
  826. if (this._updatable) {
  827. sp = this._addParticle(this.nbParticles, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo, storage);
  828. sp.position.copyFrom(currentCopy.position);
  829. sp.rotation.copyFrom(currentCopy.rotation);
  830. if (currentCopy.rotationQuaternion) {
  831. if (sp.rotationQuaternion) {
  832. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  833. }
  834. else {
  835. sp.rotationQuaternion = currentCopy.rotationQuaternion.clone();
  836. }
  837. }
  838. if (currentCopy.color) {
  839. if (sp.color) {
  840. sp.color.copyFrom(currentCopy.color);
  841. }
  842. else {
  843. sp.color = currentCopy.color.clone();
  844. }
  845. }
  846. sp.scaling.copyFrom(currentCopy.scaling);
  847. sp.uvs.copyFrom(currentCopy.uvs);
  848. if (currentCopy.materialIndex !== null) {
  849. sp.materialIndex = currentCopy.materialIndex;
  850. }
  851. if (this.expandable) {
  852. this._idxOfId[sp.id] = sp.idx;
  853. }
  854. }
  855. if (!storage) {
  856. this._index += shape.length;
  857. this.nbParticles++;
  858. this._lastParticleId++;
  859. }
  860. return sp;
  861. }
  862. /**
  863. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  864. * This method calls `updateParticle()` for each particle of the SPS.
  865. * For an animated SPS, it is usually called within the render loop.
  866. * This methods does nothing if called on a non updatable or not yet built SPS. Example : buildMesh() not called after having added or removed particles from an expandable SPS.
  867. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  868. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  869. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  870. * @returns the SPS.
  871. */
  872. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): SolidParticleSystem {
  873. if (!this._updatable || this._isNotBuilt) {
  874. return this;
  875. }
  876. // custom beforeUpdate
  877. this.beforeUpdateParticles(start, end, update);
  878. const rotMatrix = TmpVectors.Matrix[0];
  879. const invertedMatrix = TmpVectors.Matrix[1];
  880. const mesh = this.mesh;
  881. const colors32 = this._colors32;
  882. const positions32 = this._positions32;
  883. const normals32 = this._normals32;
  884. const uvs32 = this._uvs32;
  885. const indices32 = this._indices32;
  886. const indices = this._indices;
  887. const fixedNormal32 = this._fixedNormal32;
  888. const tempVectors = TmpVectors.Vector3;
  889. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  890. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  891. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  892. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  893. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  894. const camInvertedPosition = tempVectors[10].setAll(0);
  895. const tmpVertex = this._tmpVertex;
  896. const tmpVector = tmpVertex.position;
  897. const tmpColor = tmpVertex.color;
  898. const tmpUV = tmpVertex.uv;
  899. // cases when the World Matrix is to be computed first
  900. if (this.billboard || this._depthSort) {
  901. this.mesh.computeWorldMatrix(true);
  902. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  903. }
  904. // if the particles will always face the camera
  905. if (this.billboard) {
  906. // compute the camera position and un-rotate it by the current mesh rotation
  907. const tmpVector0 = tempVectors[0];
  908. this._camera.getDirectionToRef(Axis.Z, tmpVector0);
  909. Vector3.TransformNormalToRef(tmpVector0, invertedMatrix, camAxisZ);
  910. camAxisZ.normalize();
  911. // same for camera up vector extracted from the cam view matrix
  912. var view = this._camera.getViewMatrix(true);
  913. Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  914. Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  915. camAxisY.normalize();
  916. camAxisX.normalize();
  917. }
  918. // if depthSort, compute the camera global position in the mesh local system
  919. if (this._depthSort) {
  920. Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  921. }
  922. Matrix.IdentityToRef(rotMatrix);
  923. var idx = 0; // current position index in the global array positions32
  924. var index = 0; // position start index in the global array positions32 of the current particle
  925. var colidx = 0; // current color index in the global array colors32
  926. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  927. var uvidx = 0; // current uv index in the global array uvs32
  928. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  929. var pt = 0; // current index in the particle model shape
  930. if (this.mesh.isFacetDataEnabled) {
  931. this._computeBoundingBox = true;
  932. }
  933. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  934. if (this._computeBoundingBox) {
  935. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  936. const boundingInfo = this.mesh._boundingInfo;
  937. if (boundingInfo) {
  938. minimum.copyFrom(boundingInfo.minimum);
  939. maximum.copyFrom(boundingInfo.maximum);
  940. }
  941. }
  942. }
  943. // particle loop
  944. index = this.particles[start]._pos;
  945. const vpos = (index / 3) | 0;
  946. colorIndex = vpos * 4;
  947. uvIndex = vpos * 2;
  948. for (var p = start; p <= end; p++) {
  949. const particle = this.particles[p];
  950. // call to custom user function to update the particle properties
  951. this.updateParticle(particle);
  952. const shape = particle._model._shape;
  953. const shapeUV = particle._model._shapeUV;
  954. const particleRotationMatrix = particle._rotationMatrix;
  955. const particlePosition = particle.position;
  956. const particleRotation = particle.rotation;
  957. const particleScaling = particle.scaling;
  958. const particleGlobalPosition = particle._globalPosition;
  959. // camera-particle distance for depth sorting
  960. if (this._depthSort && this._depthSortParticles) {
  961. var dsp = this.depthSortedParticles[p];
  962. dsp.idx = particle.idx;
  963. dsp.ind = particle._ind;
  964. dsp.indicesLength = particle._model._indicesLength;
  965. dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition);
  966. }
  967. // skip the computations for inactive or already invisible particles
  968. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  969. // increment indexes for the next particle
  970. pt = shape.length;
  971. index += pt * 3;
  972. colorIndex += pt * 4;
  973. uvIndex += pt * 2;
  974. continue;
  975. }
  976. if (particle.isVisible) {
  977. particle._stillInvisible = false; // un-mark permanent invisibility
  978. const scaledPivot = tempVectors[12];
  979. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  980. // particle rotation matrix
  981. if (this.billboard) {
  982. particleRotation.x = 0.0;
  983. particleRotation.y = 0.0;
  984. }
  985. if (this._computeParticleRotation || this.billboard) {
  986. particle.getRotationMatrix(rotMatrix);
  987. }
  988. const particleHasParent = (particle.parentId !== null);
  989. if (particleHasParent) {
  990. const parent = this.getParticleById(particle.parentId!);
  991. if (parent) {
  992. const parentRotationMatrix = parent._rotationMatrix;
  993. const parentGlobalPosition = parent._globalPosition;
  994. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  995. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  996. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  997. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  998. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  999. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  1000. if (this._computeParticleRotation || this.billboard) {
  1001. const rotMatrixValues = rotMatrix.m;
  1002. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  1003. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  1004. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  1005. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  1006. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  1007. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  1008. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  1009. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  1010. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  1011. }
  1012. }
  1013. else { // in case the parent were removed at some moment
  1014. particle.parentId = null;
  1015. }
  1016. }
  1017. else {
  1018. particleGlobalPosition.x = particlePosition.x;
  1019. particleGlobalPosition.y = particlePosition.y;
  1020. particleGlobalPosition.z = particlePosition.z;
  1021. if (this._computeParticleRotation || this.billboard) {
  1022. const rotMatrixValues = rotMatrix.m;
  1023. particleRotationMatrix[0] = rotMatrixValues[0];
  1024. particleRotationMatrix[1] = rotMatrixValues[1];
  1025. particleRotationMatrix[2] = rotMatrixValues[2];
  1026. particleRotationMatrix[3] = rotMatrixValues[4];
  1027. particleRotationMatrix[4] = rotMatrixValues[5];
  1028. particleRotationMatrix[5] = rotMatrixValues[6];
  1029. particleRotationMatrix[6] = rotMatrixValues[8];
  1030. particleRotationMatrix[7] = rotMatrixValues[9];
  1031. particleRotationMatrix[8] = rotMatrixValues[10];
  1032. }
  1033. }
  1034. const pivotBackTranslation = tempVectors[11];
  1035. if (particle.translateFromPivot) {
  1036. pivotBackTranslation.setAll(0.0);
  1037. }
  1038. else {
  1039. pivotBackTranslation.copyFrom(scaledPivot);
  1040. }
  1041. // particle vertex loop
  1042. for (pt = 0; pt < shape.length; pt++) {
  1043. idx = index + pt * 3;
  1044. colidx = colorIndex + pt * 4;
  1045. uvidx = uvIndex + pt * 2;
  1046. const iu = 2 * pt;
  1047. const iv = iu + 1;
  1048. tmpVector.copyFrom(shape[pt]);
  1049. if (this._computeParticleColor && particle.color) {
  1050. tmpColor.copyFrom(particle.color);
  1051. }
  1052. if (this._computeParticleTexture) {
  1053. tmpUV.copyFromFloats(shapeUV[iu], shapeUV[iv]);
  1054. }
  1055. if (this._computeParticleVertex) {
  1056. this.updateParticleVertex(particle, tmpVertex, pt);
  1057. }
  1058. // positions
  1059. const vertexX = tmpVector.x * particleScaling.x - scaledPivot.x;
  1060. const vertexY = tmpVector.y * particleScaling.y - scaledPivot.y;
  1061. const vertexZ = tmpVector.z * particleScaling.z - scaledPivot.z;
  1062. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  1063. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  1064. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  1065. rotatedX += pivotBackTranslation.x;
  1066. rotatedY += pivotBackTranslation.y;
  1067. rotatedZ += pivotBackTranslation.z;
  1068. const px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  1069. const py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  1070. const pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  1071. if (this._computeBoundingBox) {
  1072. minimum.minimizeInPlaceFromFloats(px, py, pz);
  1073. maximum.maximizeInPlaceFromFloats(px, py, pz);
  1074. }
  1075. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  1076. if (!this._computeParticleVertex) {
  1077. const normalx = fixedNormal32[idx];
  1078. const normaly = fixedNormal32[idx + 1];
  1079. const normalz = fixedNormal32[idx + 2];
  1080. const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  1081. const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  1082. const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  1083. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  1084. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  1085. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  1086. }
  1087. if (this._computeParticleColor && particle.color) {
  1088. const colors32 = this._colors32;
  1089. colors32[colidx] = tmpColor.r;
  1090. colors32[colidx + 1] = tmpColor.g;
  1091. colors32[colidx + 2] = tmpColor.b;
  1092. colors32[colidx + 3] = tmpColor.a;
  1093. }
  1094. if (this._computeParticleTexture) {
  1095. const uvs = particle.uvs;
  1096. uvs32[uvidx] = tmpUV.x * (uvs.z - uvs.x) + uvs.x;
  1097. uvs32[uvidx + 1] = tmpUV.y * (uvs.w - uvs.y) + uvs.y;
  1098. }
  1099. }
  1100. }
  1101. // particle just set invisible : scaled to zero and positioned at the origin
  1102. else {
  1103. particle._stillInvisible = true; // mark the particle as invisible
  1104. for (pt = 0; pt < shape.length; pt++) {
  1105. idx = index + pt * 3;
  1106. colidx = colorIndex + pt * 4;
  1107. uvidx = uvIndex + pt * 2;
  1108. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  1109. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  1110. if (this._computeParticleColor && particle.color) {
  1111. const color = particle.color;
  1112. colors32[colidx] = color.r;
  1113. colors32[colidx + 1] = color.g;
  1114. colors32[colidx + 2] = color.b;
  1115. colors32[colidx + 3] = color.a;
  1116. }
  1117. if (this._computeParticleTexture) {
  1118. const uvs = particle.uvs;
  1119. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  1120. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  1121. }
  1122. }
  1123. }
  1124. // if the particle intersections must be computed : update the bbInfo
  1125. if (this._particlesIntersect) {
  1126. const bInfo = particle._boundingInfo;
  1127. const bBox = bInfo.boundingBox;
  1128. const bSphere = bInfo.boundingSphere;
  1129. const modelBoundingInfo = particle._modelBoundingInfo;
  1130. if (!this._bSphereOnly) {
  1131. // place, scale and rotate the particle bbox within the SPS local system, then update it
  1132. const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  1133. const tempMin = tempVectors[1];
  1134. const tempMax = tempVectors[2];
  1135. tempMin.setAll(Number.MAX_VALUE);
  1136. tempMax.setAll(-Number.MAX_VALUE);
  1137. for (var b = 0; b < 8; b++) {
  1138. const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  1139. const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  1140. const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  1141. const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  1142. const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  1143. const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  1144. const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  1145. const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  1146. const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  1147. tempMin.minimizeInPlaceFromFloats(x, y, z);
  1148. tempMax.maximizeInPlaceFromFloats(x, y, z);
  1149. }
  1150. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  1151. }
  1152. // place and scale the particle bouding sphere in the SPS local system, then update it
  1153. const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  1154. const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  1155. const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);
  1156. const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  1157. const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  1158. const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  1159. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  1160. }
  1161. // increment indexes for the next particle
  1162. index = idx + 3;
  1163. colorIndex = colidx + 4;
  1164. uvIndex = uvidx + 2;
  1165. }
  1166. // if the VBO must be updated
  1167. if (update) {
  1168. if (this._computeParticleColor) {
  1169. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  1170. }
  1171. if (this._computeParticleTexture) {
  1172. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  1173. }
  1174. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  1175. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  1176. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  1177. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  1178. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  1179. VertexData.ComputeNormals(positions32, indices32, normals32, params);
  1180. for (var i = 0; i < normals32.length; i++) {
  1181. fixedNormal32[i] = normals32[i];
  1182. }
  1183. }
  1184. if (!mesh.areNormalsFrozen) {
  1185. mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false);
  1186. }
  1187. }
  1188. if (this._depthSort && this._depthSortParticles) {
  1189. const depthSortedParticles = this.depthSortedParticles;
  1190. depthSortedParticles.sort(this._depthSortFunction);
  1191. const dspl = depthSortedParticles.length;
  1192. let sid = 0;
  1193. let faceId = 0;
  1194. for (let sorted = 0; sorted < dspl; sorted++) {
  1195. const sortedParticle = depthSortedParticles[sorted];
  1196. const lind = sortedParticle.indicesLength;
  1197. const sind = sortedParticle.ind;
  1198. for (var i = 0; i < lind; i++) {
  1199. indices32[sid] = indices[sind + i];
  1200. sid++;
  1201. if (this._pickable) {
  1202. let f = i % 3;
  1203. if (f == 0) {
  1204. let pickedData = this.pickedParticles[faceId];
  1205. pickedData.idx = sortedParticle.idx;
  1206. pickedData.faceId = faceId;
  1207. faceId++;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. mesh.updateIndices(indices32);
  1213. }
  1214. }
  1215. if (this._computeBoundingBox) {
  1216. if (mesh._boundingInfo) {
  1217. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  1218. }
  1219. else {
  1220. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  1221. }
  1222. }
  1223. if (this._autoUpdateSubMeshes) {
  1224. this.computeSubMeshes();
  1225. }
  1226. this.afterUpdateParticles(start, end, update);
  1227. return this;
  1228. }
  1229. /**
  1230. * Disposes the SPS.
  1231. */
  1232. public dispose(): void {
  1233. this.mesh.dispose();
  1234. this.vars = null;
  1235. // drop references to internal big arrays for the GC
  1236. (<any>this._positions) = null;
  1237. (<any>this._indices) = null;
  1238. (<any>this._normals) = null;
  1239. (<any>this._uvs) = null;
  1240. (<any>this._colors) = null;
  1241. (<any>this._indices32) = null;
  1242. (<any>this._positions32) = null;
  1243. (<any>this._normals32) = null;
  1244. (<any>this._fixedNormal32) = null;
  1245. (<any>this._uvs32) = null;
  1246. (<any>this._colors32) = null;
  1247. (<any>this.pickedParticles) = null;
  1248. (<any>this.pickedBySubMesh) = null;
  1249. (<any>this._materials) = null;
  1250. (<any>this._materialIndexes) = null;
  1251. (<any>this._indicesByMaterial) = null;
  1252. (<any>this._idxOfId) = null;
  1253. }
  1254. /** Returns an object {idx: numbern faceId: number} for the picked particle from the passed pickingInfo object.
  1255. * idx is the particle index in the SPS
  1256. * faceId is the picked face index counted within this particle.
  1257. * Returns null if the pickInfo can't identify a picked particle.
  1258. * @param pickingInfo (PickingInfo object)
  1259. * @returns {idx: number, faceId: number} or null
  1260. */
  1261. public pickedParticle(pickingInfo: PickingInfo): Nullable<{idx: number, faceId: number}> {
  1262. if (pickingInfo.hit) {
  1263. const subMesh = pickingInfo.subMeshId;
  1264. const faceId = pickingInfo.faceId;
  1265. const picked = this.pickedBySubMesh;
  1266. if (picked[subMesh] && picked[subMesh][faceId]) {
  1267. return picked[subMesh][faceId];
  1268. }
  1269. }
  1270. return null;
  1271. }
  1272. /**
  1273. * Returns a SolidParticle object from its identifier : particle.id
  1274. * @param id (integer) the particle Id
  1275. * @returns the searched particle or null if not found in the SPS.
  1276. */
  1277. public getParticleById(id: number): Nullable<SolidParticle> {
  1278. const p = this.particles[id];
  1279. if (p && p.id == id) {
  1280. return p;
  1281. }
  1282. const particles = this.particles;
  1283. const idx = this._idxOfId[id];
  1284. if (idx !== undefined) {
  1285. return particles[idx];
  1286. }
  1287. var i = 0;
  1288. const nb = this.nbParticles;
  1289. while (i < nb) {
  1290. var particle = particles[i];
  1291. if (particle.id == id) {
  1292. return particle;
  1293. }
  1294. i++;
  1295. }
  1296. return null;
  1297. }
  1298. /**
  1299. * Returns a new array populated with the particles having the passed shapeId.
  1300. * @param shapeId (integer) the shape identifier
  1301. * @returns a new solid particle array
  1302. */
  1303. public getParticlesByShapeId(shapeId: number): SolidParticle[] {
  1304. var ref: SolidParticle[] = [];
  1305. this.getParticlesByShapeIdToRef(shapeId, ref);
  1306. return ref;
  1307. }
  1308. /**
  1309. * Populates the passed array "ref" with the particles having the passed shapeId.
  1310. * @param shapeId the shape identifier
  1311. * @returns the SPS
  1312. * @param ref
  1313. */
  1314. public getParticlesByShapeIdToRef(shapeId: number, ref: SolidParticle[]): SolidParticleSystem {
  1315. ref.length = 0;
  1316. for (var i = 0; i < this.nbParticles; i++) {
  1317. var p = this.particles[i];
  1318. if (p.shapeId == shapeId) {
  1319. ref.push(p);
  1320. }
  1321. }
  1322. return this;
  1323. }
  1324. /**
  1325. * Computes the required SubMeshes according the materials assigned to the particles.
  1326. * @returns the solid particle system.
  1327. * Does nothing if called before the SPS mesh is built.
  1328. */
  1329. public computeSubMeshes(): SolidParticleSystem {
  1330. if (!this.mesh || !this._multimaterialEnabled) {
  1331. return this;
  1332. }
  1333. const depthSortedParticles = this.depthSortedParticles;
  1334. if (this.particles.length > 0) {
  1335. for (let p = 0; p < this.particles.length; p++) {
  1336. let part = this.particles[p];
  1337. if (!part.materialIndex) {
  1338. part.materialIndex = 0;
  1339. }
  1340. let sortedPart = depthSortedParticles[p];
  1341. sortedPart.materialIndex = part.materialIndex;
  1342. sortedPart.ind = part._ind;
  1343. sortedPart.indicesLength = part._model._indicesLength;
  1344. sortedPart.idx = part.idx;
  1345. }
  1346. }
  1347. this._sortParticlesByMaterial();
  1348. const indicesByMaterial = this._indicesByMaterial;
  1349. const materialIndexes = this._materialIndexes;
  1350. const mesh = this.mesh;
  1351. mesh.subMeshes = [];
  1352. const vcount = mesh.getTotalVertices();
  1353. for (let m = 0; m < materialIndexes.length; m++) {
  1354. let start = indicesByMaterial[m];
  1355. let count = indicesByMaterial[m + 1] - start;
  1356. let matIndex = materialIndexes[m];
  1357. new SubMesh(matIndex, 0, vcount, start, count, mesh);
  1358. }
  1359. return this;
  1360. }
  1361. /**
  1362. * Sorts the solid particles by material when MultiMaterial is enabled.
  1363. * Updates the indices32 array.
  1364. * Updates the indicesByMaterial array.
  1365. * Updates the mesh indices array.
  1366. * @returns the SPS
  1367. * @hidden
  1368. */
  1369. private _sortParticlesByMaterial(): SolidParticleSystem {
  1370. const indicesByMaterial = [0];
  1371. this._indicesByMaterial = indicesByMaterial;
  1372. const materialIndexes: number[] = [];
  1373. this._materialIndexes = materialIndexes;
  1374. const depthSortedParticles = this.depthSortedParticles;
  1375. depthSortedParticles.sort(this._materialSortFunction);
  1376. const length = depthSortedParticles.length;
  1377. const indices32 = this._indices32;
  1378. const indices = this._indices;
  1379. let subMeshIndex = 0;
  1380. let subMeshFaceId = 0;
  1381. let sid = 0;
  1382. let lastMatIndex = depthSortedParticles[0].materialIndex;
  1383. materialIndexes.push(lastMatIndex);
  1384. if (this._pickable) {
  1385. this.pickedBySubMesh = [[]];
  1386. this.pickedParticles = this.pickedBySubMesh[0];
  1387. }
  1388. for (let sorted = 0; sorted < length; sorted++) {
  1389. let sortedPart = depthSortedParticles[sorted];
  1390. let lind = sortedPart.indicesLength;
  1391. let sind = sortedPart.ind;
  1392. if (sortedPart.materialIndex !== lastMatIndex) {
  1393. lastMatIndex = sortedPart.materialIndex;
  1394. indicesByMaterial.push(sid);
  1395. materialIndexes.push(lastMatIndex);
  1396. if (this._pickable) {
  1397. subMeshIndex++;
  1398. this.pickedBySubMesh[subMeshIndex] = [];
  1399. subMeshFaceId = 0;
  1400. }
  1401. }
  1402. let faceId = 0;
  1403. for (let i = 0; i < lind; i++) {
  1404. indices32[sid] = indices[sind + i];
  1405. if (this._pickable) {
  1406. let f = i % 3;
  1407. if (f == 0) {
  1408. let pickedData = this.pickedBySubMesh[subMeshIndex][subMeshFaceId];
  1409. if (pickedData) {
  1410. pickedData.idx = sortedPart.idx;
  1411. pickedData.faceId = faceId;
  1412. }
  1413. else {
  1414. this.pickedBySubMesh[subMeshIndex][subMeshFaceId] = {idx: sortedPart.idx, faceId: faceId};
  1415. }
  1416. subMeshFaceId++;
  1417. faceId++;
  1418. }
  1419. }
  1420. sid++;
  1421. }
  1422. }
  1423. indicesByMaterial.push(indices32.length); // add the last number to ease the indices start/count values for subMeshes creation
  1424. if (this._updatable) {
  1425. this.mesh.updateIndices(indices32);
  1426. }
  1427. return this;
  1428. }
  1429. /**
  1430. * Sets the material indexes by id materialIndexesById[id] = materialIndex
  1431. * @hidden
  1432. */
  1433. private _setMaterialIndexesById() {
  1434. this._materialIndexesById = {};
  1435. for (var i = 0; i < this._materials.length; i++) {
  1436. var id = this._materials[i].uniqueId;
  1437. this._materialIndexesById[id] = i;
  1438. }
  1439. }
  1440. /**
  1441. * Returns an array with unique values of Materials from the passed array
  1442. * @param array the material array to be checked and filtered
  1443. * @hidden
  1444. */
  1445. private _filterUniqueMaterialId(array: Material[]): Material[] {
  1446. var filtered = array.filter(function(value, index, self) {
  1447. return self.indexOf(value) === index;
  1448. });
  1449. return filtered;
  1450. }
  1451. /**
  1452. * Sets a new Standard Material as _defaultMaterial if not already set.
  1453. * @hidden
  1454. */
  1455. private _setDefaultMaterial(): Material {
  1456. if (!this._defaultMaterial) {
  1457. this._defaultMaterial = new StandardMaterial(this.name + "DefaultMaterial", this._scene);
  1458. }
  1459. return this._defaultMaterial;
  1460. }
  1461. /**
  1462. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  1463. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1464. * @returns the SPS.
  1465. */
  1466. public refreshVisibleSize(): SolidParticleSystem {
  1467. if (!this._isVisibilityBoxLocked) {
  1468. this.mesh.refreshBoundingInfo();
  1469. }
  1470. return this;
  1471. }
  1472. /**
  1473. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  1474. * @param size the size (float) of the visibility box
  1475. * note : this doesn't lock the SPS mesh bounding box.
  1476. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1477. */
  1478. public setVisibilityBox(size: number): void {
  1479. var vis = size / 2;
  1480. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  1481. }
  1482. /**
  1483. * Gets whether the SPS as always visible or not
  1484. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1485. */
  1486. public get isAlwaysVisible(): boolean {
  1487. return this._alwaysVisible;
  1488. }
  1489. /**
  1490. * Sets the SPS as always visible or not
  1491. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1492. */
  1493. public set isAlwaysVisible(val: boolean) {
  1494. this._alwaysVisible = val;
  1495. this.mesh.alwaysSelectAsActiveMesh = val;
  1496. }
  1497. /**
  1498. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  1499. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1500. */
  1501. public set isVisibilityBoxLocked(val: boolean) {
  1502. this._isVisibilityBoxLocked = val;
  1503. let boundingInfo = this.mesh.getBoundingInfo();
  1504. boundingInfo.isLocked = val;
  1505. }
  1506. /**
  1507. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  1508. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1509. */
  1510. public get isVisibilityBoxLocked(): boolean {
  1511. return this._isVisibilityBoxLocked;
  1512. }
  1513. /**
  1514. * Tells to `setParticles()` to compute the particle rotations or not.
  1515. * Default value : true. The SPS is faster when it's set to false.
  1516. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  1517. */
  1518. public set computeParticleRotation(val: boolean) {
  1519. this._computeParticleRotation = val;
  1520. }
  1521. /**
  1522. * Tells to `setParticles()` to compute the particle colors or not.
  1523. * Default value : true. The SPS is faster when it's set to false.
  1524. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  1525. */
  1526. public set computeParticleColor(val: boolean) {
  1527. this._computeParticleColor = val;
  1528. }
  1529. public set computeParticleTexture(val: boolean) {
  1530. this._computeParticleTexture = val;
  1531. }
  1532. /**
  1533. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  1534. * Default value : false. The SPS is faster when it's set to false.
  1535. * Note : the particle custom vertex positions aren't stored values.
  1536. */
  1537. public set computeParticleVertex(val: boolean) {
  1538. this._computeParticleVertex = val;
  1539. }
  1540. /**
  1541. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  1542. */
  1543. public set computeBoundingBox(val: boolean) {
  1544. this._computeBoundingBox = val;
  1545. }
  1546. /**
  1547. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  1548. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  1549. * Default : `true`
  1550. */
  1551. public set depthSortParticles(val: boolean) {
  1552. this._depthSortParticles = val;
  1553. }
  1554. /**
  1555. * Gets if `setParticles()` computes the particle rotations or not.
  1556. * Default value : true. The SPS is faster when it's set to false.
  1557. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  1558. */
  1559. public get computeParticleRotation(): boolean {
  1560. return this._computeParticleRotation;
  1561. }
  1562. /**
  1563. * Gets if `setParticles()` computes the particle colors or not.
  1564. * Default value : true. The SPS is faster when it's set to false.
  1565. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  1566. */
  1567. public get computeParticleColor(): boolean {
  1568. return this._computeParticleColor;
  1569. }
  1570. /**
  1571. * Gets if `setParticles()` computes the particle textures or not.
  1572. * Default value : true. The SPS is faster when it's set to false.
  1573. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  1574. */
  1575. public get computeParticleTexture(): boolean {
  1576. return this._computeParticleTexture;
  1577. }
  1578. /**
  1579. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  1580. * Default value : false. The SPS is faster when it's set to false.
  1581. * Note : the particle custom vertex positions aren't stored values.
  1582. */
  1583. public get computeParticleVertex(): boolean {
  1584. return this._computeParticleVertex;
  1585. }
  1586. /**
  1587. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  1588. */
  1589. public get computeBoundingBox(): boolean {
  1590. return this._computeBoundingBox;
  1591. }
  1592. /**
  1593. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  1594. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  1595. * Default : `true`
  1596. */
  1597. public get depthSortParticles(): boolean {
  1598. return this._depthSortParticles;
  1599. }
  1600. /**
  1601. * Gets if the SPS is created as expandable at construction time.
  1602. * Default : `false`
  1603. */
  1604. public get expandable(): boolean {
  1605. return this._expandable;
  1606. }
  1607. /**
  1608. * Gets if the SPS supports the Multi Materials
  1609. */
  1610. public get multimaterialEnabled(): boolean {
  1611. return this._multimaterialEnabled;
  1612. }
  1613. /**
  1614. * Gets if the SPS uses the model materials for its own multimaterial.
  1615. */
  1616. public get useModelMaterial(): boolean {
  1617. return this._useModelMaterial;
  1618. }
  1619. /**
  1620. * The SPS used material array.
  1621. */
  1622. public get materials(): Material[] {
  1623. return this._materials;
  1624. }
  1625. /**
  1626. * Sets the SPS MultiMaterial from the passed materials.
  1627. * Note : the passed array is internally copied and not used then by reference.
  1628. * @param materials an array of material objects. This array indexes are the materialIndex values of the particles.
  1629. */
  1630. public setMultiMaterial(materials: Material[]) {
  1631. this._materials = this._filterUniqueMaterialId(materials);
  1632. this._setMaterialIndexesById();
  1633. if (this._multimaterial) {
  1634. this._multimaterial.dispose();
  1635. }
  1636. this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene);
  1637. for (var m = 0; m < this._materials.length; m++) {
  1638. this._multimaterial.subMaterials.push(this._materials[m]);
  1639. }
  1640. this.computeSubMeshes();
  1641. this.mesh.material = this._multimaterial;
  1642. }
  1643. /**
  1644. * The SPS computed multimaterial object
  1645. */
  1646. public get multimaterial(): MultiMaterial {
  1647. return this._multimaterial;
  1648. }
  1649. public set multimaterial(mm) {
  1650. this._multimaterial = mm;
  1651. }
  1652. /**
  1653. * If the subMeshes must be updated on the next call to setParticles()
  1654. */
  1655. public get autoUpdateSubMeshes(): boolean {
  1656. return this._autoUpdateSubMeshes;
  1657. }
  1658. public set autoUpdateSubMeshes(val: boolean) {
  1659. this._autoUpdateSubMeshes = val;
  1660. }
  1661. // =======================================================================
  1662. // Particle behavior logic
  1663. // these following methods may be overwritten by the user to fit his needs
  1664. /**
  1665. * This function does nothing. It may be overwritten to set all the particle first values.
  1666. * The SPS doesn't call this function, you may have to call it by your own.
  1667. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1668. */
  1669. public initParticles(): void {
  1670. }
  1671. /**
  1672. * This function does nothing. It may be overwritten to recycle a particle.
  1673. * The SPS doesn't call this function, you may have to call it by your own.
  1674. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1675. * @param particle The particle to recycle
  1676. * @returns the recycled particle
  1677. */
  1678. public recycleParticle(particle: SolidParticle): SolidParticle {
  1679. return particle;
  1680. }
  1681. /**
  1682. * Updates a particle : this function should be overwritten by the user.
  1683. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  1684. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1685. * @example : just set a particle position or velocity and recycle conditions
  1686. * @param particle The particle to update
  1687. * @returns the updated particle
  1688. */
  1689. public updateParticle(particle: SolidParticle): SolidParticle {
  1690. return particle;
  1691. }
  1692. /**
  1693. * Updates a vertex of a particle : it can be overwritten by the user.
  1694. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  1695. * @param particle the current particle
  1696. * @param vertex the current vertex of the current particle : a SolidParticleVertex object
  1697. * @param pt the index of the current vertex in the particle shape
  1698. * doc : https://doc.babylonjs.com/how_to/Solid_Particle_System#update-each-particle-shape
  1699. * @example : just set a vertex particle position or color
  1700. * @returns the sps
  1701. */
  1702. public updateParticleVertex(particle: SolidParticle, vertex: SolidParticleVertex, pt: number): SolidParticleSystem {
  1703. return this;
  1704. }
  1705. /**
  1706. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  1707. * This does nothing and may be overwritten by the user.
  1708. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1709. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1710. * @param update the boolean update value actually passed to setParticles()
  1711. */
  1712. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1713. }
  1714. /**
  1715. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  1716. * This will be passed three parameters.
  1717. * This does nothing and may be overwritten by the user.
  1718. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1719. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1720. * @param update the boolean update value actually passed to setParticles()
  1721. */
  1722. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1723. }
  1724. }