pointsCloudSystem.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. import { IndicesArray, FloatArray } from "../types";
  2. import { Color4, Color3 } from "../Maths/math";
  3. import { Vector2, Vector3, Vector4, TmpVectors, Matrix } from "../Maths/math.vector";
  4. import { Logger } from "../Misc/logger";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { VertexData } from "../Meshes/mesh.vertexData";
  7. import { Mesh } from "../Meshes/mesh";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { Scene, IDisposable } from "../scene";
  10. import { CloudPoint, PointsGroup } from "./cloudPoint";
  11. import { BoundingInfo } from "../Culling/boundingInfo";
  12. import { Ray } from "../Culling/ray";
  13. import { PickingInfo } from "../Collisions/pickingInfo";
  14. import { StandardMaterial } from "../Materials/standardMaterial";
  15. import { Texture } from "./../Materials/Textures/texture";
  16. import { Scalar } from "../Maths/math.scalar";
  17. /** Defines the 3 color options */
  18. export class PointColor {
  19. /** color value */
  20. public static COLOR: number = 2;
  21. /** uv value */
  22. public static UV: number = 1;
  23. /** random value */
  24. public static RANDOM: number = 0;
  25. /** color value */
  26. public static STATED: number = 3;
  27. }
  28. /**
  29. * The PointCloudSystem (PCS) is a single updatable mesh. The points corresponding to the vertices of this big mesh.
  30. * As it is just a mesh, the PointCloudSystem has all the same properties as any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  31. * The PointCloudSytem is also a particle system, with each point being a particle. It provides some methods to manage the particles.
  32. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  33. *
  34. * Full documentation here : TO BE ENTERED
  35. */
  36. export class PointsCloudSystem implements IDisposable {
  37. /**
  38. * The PCS array of cloud point objects. Just access each particle as with any classic array.
  39. * Example : var p = SPS.particles[i];
  40. */
  41. public particles: CloudPoint[] = new Array<CloudPoint>();
  42. /**
  43. * The PCS total number of particles. Read only. Use PCS.counter instead if you need to set your own value.
  44. */
  45. public nbParticles: number = 0;
  46. /**
  47. * This a counter for your own usage. It's not set by any SPS functions.
  48. */
  49. public counter: number = 0;
  50. /**
  51. * The PCS name. This name is also given to the underlying mesh.
  52. */
  53. public name: string;
  54. /**
  55. * The PCS 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 PCS specific or temporary values in order to lower the Garbage Collector activity.
  60. * Please read :
  61. */
  62. public vars: any = {};
  63. /**
  64. * @hidden
  65. */
  66. public _size: number; //size of each point particle
  67. private _scene: Scene;
  68. private _promises: Array<Promise<any>> = [];
  69. private _positions: number[] = new Array<number>();
  70. private _indices: number[] = new Array<number>();
  71. private _normals: number[] = new Array<number>();
  72. private _colors: number[] = new Array<number>();
  73. private _uvs: number[] = new Array<number>();
  74. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  75. private _positions32: Float32Array; // updated positions for the VBO
  76. private _colors32: Float32Array;
  77. private _uvs32: Float32Array;
  78. private _updatable: boolean = true;
  79. private _isVisibilityBoxLocked = false;
  80. private _alwaysVisible: boolean = false;
  81. private _groups: number[] = new Array<number>(); //start indices for each group of particles
  82. private _groupCounter: number = 0;
  83. private _computeParticleColor: boolean = true;
  84. private _computeParticleTexture: boolean = true;
  85. private _computeParticleRotation: boolean = true;
  86. private _computeBoundingBox: boolean = false;
  87. private _isReady: boolean = false;
  88. /**
  89. * Creates a PCS (Points Cloud System) object
  90. * @param name (String) is the PCS name, this will be the underlying mesh name
  91. * @param pointSize (number) is the size for each point
  92. * @param scene (Scene) is the scene in which the PCS is added
  93. * @param options defines the options of the sps e.g.
  94. * * updatable (optional boolean, default true) : if the PCS must be updatable or immutable
  95. * * particleIntersection (optional boolean, default false) : if the particle intersections must be computed
  96. */
  97. constructor(name: string, pointSize: number, scene: Scene, options?: { updatable?: boolean}) {
  98. this.name = name;
  99. this._size = pointSize;
  100. this._scene = scene || EngineStore.LastCreatedScene;
  101. if (options && options.updatable !== undefined) {
  102. this._updatable = options.updatable;
  103. } else {
  104. this._updatable = true;
  105. }
  106. }
  107. /**
  108. * Builds the PCS underlying mesh. Returns a standard Mesh.
  109. * If no points were added to the PCS, the returned mesh is just a single point.
  110. * @returns a promise for the created mesh
  111. */
  112. public buildMeshAsync(): Promise<Mesh> {
  113. return Promise.all(this._promises).then(() => {
  114. this._isReady = true;
  115. return this._buildMesh();
  116. });
  117. }
  118. /**
  119. * @hidden
  120. */
  121. private _buildMesh(): Promise<Mesh> {
  122. if (this.nbParticles === 0) {
  123. this.addPoints(1);
  124. }
  125. this._positions32 = new Float32Array(this._positions);
  126. this._uvs32 = new Float32Array(this._uvs);
  127. this._colors32 = new Float32Array(this._colors);
  128. var vertexData = new VertexData();
  129. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  130. if (this._uvs32.length > 0) {
  131. vertexData.set(this._uvs32, VertexBuffer.UVKind);
  132. }
  133. var ec = 0; //emissive color value 0 for UVs, 1 for color
  134. if (this._colors32.length > 0) {
  135. ec = 1;
  136. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  137. }
  138. var mesh = new Mesh(this.name, this._scene);
  139. vertexData.applyToMesh(mesh, this._updatable);
  140. this.mesh = mesh;
  141. // free memory
  142. (<any>this._positions) = null;
  143. (<any>this._uvs) = null;
  144. (<any>this._colors) = null;
  145. if (!this._updatable) {
  146. this.particles.length = 0;
  147. }
  148. var mat = new StandardMaterial("point cloud material", this._scene);
  149. mat.emissiveColor = new Color3(ec, ec, ec);
  150. mat.disableLighting = true;
  151. mat.pointsCloud = true;
  152. mat.pointSize = this._size;
  153. mesh.material = mat;
  154. return new Promise((resolve) => resolve(mesh));
  155. }
  156. // adds a new particle object in the particles array
  157. private _addParticle(idx: number, group: PointsGroup, groupId: number, idxInGroup: number): CloudPoint {
  158. var cp = new CloudPoint(idx, group, groupId, idxInGroup, this);
  159. this.particles.push(cp);
  160. return cp;
  161. }
  162. private _randomUnitVector(particle: CloudPoint): void {
  163. particle.position = new Vector3(Math.random(), Math.random(), Math.random());
  164. particle.color = new Color4(1, 1, 1, 1);
  165. }
  166. private _getColorIndicesForCoord(pointsGroup: PointsGroup, x: number, y: number, width: number): Color4 {
  167. var imageData = <Uint8Array>pointsGroup._groupImageData;
  168. var color = y * (width * 4) + x * 4;
  169. var colorIndices = [color, color + 1, color + 2, color + 3];
  170. var redIndex = colorIndices[0];
  171. var greenIndex = colorIndices[1];
  172. var blueIndex = colorIndices[2];
  173. var alphaIndex = colorIndices[3];
  174. var redForCoord = imageData[redIndex];
  175. var greenForCoord = imageData[greenIndex];
  176. var blueForCoord = imageData[blueIndex];
  177. var alphaForCoord = imageData[alphaIndex];
  178. return new Color4(redForCoord / 255, greenForCoord / 255, blueForCoord / 255, alphaForCoord);
  179. }
  180. private _setPointsColorOrUV(mesh: Mesh, pointsGroup: PointsGroup, isVolume: boolean, colorFromTexture?: boolean, hasTexture?: boolean, color?: Color4, range?: number) {
  181. if (isVolume) {
  182. mesh.updateFacetData();
  183. }
  184. var boundInfo = mesh.getBoundingInfo();
  185. var diameter = 2 * boundInfo.boundingSphere.radius;
  186. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  187. var meshInd = <IndicesArray>mesh.getIndices();
  188. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  189. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  190. var place = Vector3.Zero();
  191. mesh.computeWorldMatrix();
  192. var meshMatrix: Matrix = mesh.getWorldMatrix();
  193. if (!meshMatrix.isIdentity()) {
  194. for (var p = 0; p < meshPos.length / 3; p++) {
  195. Vector3.TransformCoordinatesFromFloatsToRef(meshPos[3 * p], meshPos[3 * p + 1], meshPos[3 * p + 2], meshMatrix, place);
  196. meshPos[3 * p] = place.x;
  197. meshPos[3 * p + 1] = place.y;
  198. meshPos[3 * p + 2] = place.z;
  199. }
  200. }
  201. var idxPoints: number = 0;
  202. var index: number = 0;
  203. var id0: number = 0;
  204. var id1: number = 0;
  205. var id2: number = 0;
  206. var v0X: number = 0;
  207. var v0Y: number = 0;
  208. var v0Z: number = 0;
  209. var v1X: number = 0;
  210. var v1Y: number = 0;
  211. var v1Z: number = 0;
  212. var v2X: number = 0;
  213. var v2Y: number = 0;
  214. var v2Z: number = 0;
  215. var vertex0 = Vector3.Zero();
  216. var vertex1 = Vector3.Zero();
  217. var vertex2 = Vector3.Zero();
  218. var vec0 = Vector3.Zero();
  219. var vec1 = Vector3.Zero();
  220. var uv0X: number = 0;
  221. var uv0Y: number = 0;
  222. var uv1X: number = 0;
  223. var uv1Y: number = 0;
  224. var uv2X: number = 0;
  225. var uv2Y: number = 0;
  226. var uv0 = Vector2.Zero();
  227. var uv1 = Vector2.Zero();
  228. var uv2 = Vector2.Zero();
  229. var uvec0 = Vector2.Zero();
  230. var uvec1 = Vector2.Zero();
  231. var col0X: number = 0;
  232. var col0Y: number = 0;
  233. var col0Z: number = 0;
  234. var col0A: number = 0;
  235. var col1X: number = 0;
  236. var col1Y: number = 0;
  237. var col1Z: number = 0;
  238. var col1A: number = 0;
  239. var col2X: number = 0;
  240. var col2Y: number = 0;
  241. var col2Z: number = 0;
  242. var col2A: number = 0;
  243. var col0 = Vector4.Zero();
  244. var col1 = Vector4.Zero();
  245. var col2 = Vector4.Zero();
  246. var colvec0 = Vector4.Zero();
  247. var colvec1 = Vector4.Zero();
  248. var lamda: number = 0;
  249. var mu: number = 0;
  250. range = range ? range : 0;
  251. var facetPoint: Vector3;
  252. var uvPoint: Vector2;
  253. var colPoint: Vector4 = new Vector4(0, 0, 0, 0);
  254. var norm = Vector3.Zero();
  255. var tang = Vector3.Zero();
  256. var biNorm = Vector3.Zero();
  257. var angle = 0;
  258. var facetPlaneVec = Vector3.Zero();
  259. var gap = 0;
  260. var distance = 0;
  261. var ray = new Ray(Vector3.Zero(), new Vector3(1, 0, 0));
  262. var pickInfo: PickingInfo;
  263. var direction = Vector3.Zero();
  264. for (var index = 0; index < meshInd.length / 3; index++) {
  265. id0 = meshInd[3 * index];
  266. id1 = meshInd[3 * index + 1];
  267. id2 = meshInd[3 * index + 2];
  268. v0X = meshPos[3 * id0];
  269. v0Y = meshPos[3 * id0 + 1];
  270. v0Z = meshPos[3 * id0 + 2];
  271. v1X = meshPos[3 * id1];
  272. v1Y = meshPos[3 * id1 + 1];
  273. v1Z = meshPos[3 * id1 + 2];
  274. v2X = meshPos[3 * id2];
  275. v2Y = meshPos[3 * id2 + 1];
  276. v2Z = meshPos[3 * id2 + 2];
  277. vertex0.set(v0X, v0Y, v0Z);
  278. vertex1.set(v1X, v1Y, v1Z);
  279. vertex2.set(v2X, v2Y, v2Z);
  280. vertex1.subtractToRef(vertex0, vec0);
  281. vertex2.subtractToRef(vertex1, vec1);
  282. if (meshUV) {
  283. uv0X = meshUV[2 * id0];
  284. uv0Y = meshUV[2 * id0 + 1];
  285. uv1X = meshUV[2 * id1];
  286. uv1Y = meshUV[2 * id1 + 1];
  287. uv2X = meshUV[2 * id2];
  288. uv2Y = meshUV[2 * id2 + 1];
  289. uv0.set(uv0X, uv0Y);
  290. uv1.set(uv1X, uv1Y);
  291. uv2.set(uv2X, uv2Y);
  292. uv1.subtractToRef(uv0, uvec0);
  293. uv2.subtractToRef(uv1, uvec1);
  294. }
  295. if (meshCol && colorFromTexture) {
  296. col0X = meshCol[4 * id0];
  297. col0Y = meshCol[4 * id0 + 1];
  298. col0Z = meshCol[4 * id0 + 2];
  299. col0A = meshCol[4 * id0 + 3];
  300. col1X = meshCol[4 * id1];
  301. col1Y = meshCol[4 * id1 + 1];
  302. col1Z = meshCol[4 * id1 + 2];
  303. col1A = meshCol[4 * id1 + 3];
  304. col2X = meshCol[4 * id2];
  305. col2Y = meshCol[4 * id2 + 1];
  306. col2Z = meshCol[4 * id2 + 2];
  307. col2A = meshCol[4 * id2 + 3];
  308. col0.set(col0X, col0Y, col0Z, col0A);
  309. col1.set(col1X, col1Y, col1Z, col1A);
  310. col2.set(col2X, col2Y, col2Z, col2A);
  311. col1.subtractToRef(col0, colvec0);
  312. col2.subtractToRef(col1, colvec1);
  313. }
  314. var width: number;
  315. var height: number;
  316. var deltaS: number;
  317. var deltaV: number;
  318. var h: number;
  319. var s: number;
  320. var v: number;
  321. var hsvCol: Color3;
  322. var statedColor: Color3 = new Color3(0, 0, 0);
  323. var colPoint3: Color3 = new Color3(0, 0, 0);
  324. var pointColors: Color4;
  325. var particle: CloudPoint;
  326. for (var i = 0; i < pointsGroup._groupDensity[index]; i++) {
  327. idxPoints = this.particles.length;
  328. this._addParticle(idxPoints, pointsGroup, this._groupCounter, index + i);
  329. particle = this.particles[idxPoints];
  330. //form a point inside the facet v0, v1, v2;
  331. lamda = Scalar.RandomRange(0, 1);
  332. mu = Scalar.RandomRange(0, 1);
  333. facetPoint = vertex0.add(vec0.scale(lamda)).add(vec1.scale(lamda * mu));
  334. if (isVolume) {
  335. norm = mesh.getFacetNormal(index).normalize().scale(-1);
  336. tang = vec0.clone().normalize();
  337. biNorm = Vector3.Cross(norm, tang);
  338. angle = Scalar.RandomRange(0, 2 * Math.PI);
  339. facetPlaneVec = tang.scale(Math.cos(angle)).add(biNorm.scale(Math.sin(angle)));
  340. angle = Scalar.RandomRange(0.1, Math.PI / 2);
  341. direction = facetPlaneVec.scale(Math.cos(angle)).add(norm.scale(Math.sin(angle)));
  342. ray.origin = facetPoint.add(direction.scale(0.00001));
  343. ray.direction = direction;
  344. ray.length = diameter;
  345. pickInfo = ray.intersectsMesh(mesh);
  346. if (pickInfo.hit) {
  347. distance = pickInfo.pickedPoint!.subtract(facetPoint).length();
  348. gap = Scalar.RandomRange(0, 1) * distance;
  349. facetPoint.addInPlace(direction.scale(gap));
  350. }
  351. }
  352. particle.position = facetPoint.clone();
  353. this._positions.push(particle.position.x, particle.position.y, particle.position.z);
  354. if (colorFromTexture !== undefined) {
  355. if (meshUV) {
  356. uvPoint = uv0.add(uvec0.scale(lamda)).add(uvec1.scale(lamda * mu));
  357. if (colorFromTexture) { //Set particle color to texture color
  358. if (hasTexture && pointsGroup._groupImageData !== null) {
  359. width = pointsGroup._groupImgWidth;
  360. height = pointsGroup._groupImgHeight;
  361. pointColors = this._getColorIndicesForCoord(pointsGroup, Math.floor(uvPoint.x * width), Math.round((1 - uvPoint.y) * height), width);
  362. particle.color = pointColors;
  363. this._colors.push(pointColors.r, pointColors.g, pointColors.b, pointColors.a);
  364. }
  365. else {
  366. if (meshCol) { //failure in texture and colors available
  367. colPoint = col0.add(colvec0.scale(lamda)).add(colvec1.scale(lamda * mu));
  368. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  369. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  370. }
  371. else {
  372. colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);
  373. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  374. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  375. }
  376. }
  377. }
  378. else { //Set particle uv based on a mesh uv
  379. particle.uv = uvPoint.clone();
  380. this._uvs.push(particle.uv.x, particle.uv.y);
  381. }
  382. }
  383. }
  384. else {
  385. if (color) {
  386. statedColor.set(color.r, color.g, color.b);
  387. deltaS = Scalar.RandomRange(-range, range);
  388. deltaV = Scalar.RandomRange(-range, range);
  389. hsvCol = statedColor.toHSV();
  390. h = hsvCol.r;
  391. s = hsvCol.g + deltaS;
  392. v = hsvCol.b + deltaV;
  393. if (s < 0) {
  394. s = 0;
  395. }
  396. if (s > 1) {
  397. s = 1;
  398. }
  399. if (h < 0) {
  400. h = 0;
  401. }
  402. if (h > 1) {
  403. h = 1;
  404. }
  405. Color3.HSVtoRGBToRef(h, s, v, colPoint3);
  406. colPoint.set(colPoint3.r, colPoint3.g, colPoint3.b, 1);
  407. }
  408. else {
  409. colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);
  410. }
  411. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  412. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  413. }
  414. }
  415. }
  416. }
  417. // stores mesh texture in dynamic texture for color pixel retrieval
  418. // when pointColor type is color for surface points
  419. private _colorFromTexture(mesh: Mesh, pointsGroup: PointsGroup, isVolume: boolean): void {
  420. if (mesh.material === null) {
  421. Logger.Warn(mesh.name + "has no material.");
  422. pointsGroup._groupImageData = null;
  423. this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);
  424. return;
  425. }
  426. var mat = <StandardMaterial>mesh.material;
  427. if (mat.diffuseTexture === null && mat.emissiveTexture === null) {
  428. Logger.Warn(mesh.name + "has no useable texture.");
  429. pointsGroup._groupImageData = null;
  430. this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);
  431. return;
  432. }
  433. if (mat.diffuseTexture!._texture === null && mat.emissiveTexture!._texture === null) {
  434. Logger.Warn(mesh.name + "has no useable texture.");
  435. pointsGroup._groupImageData = null;
  436. this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);
  437. return;
  438. }
  439. var clone = <Mesh>mesh.clone();
  440. clone.setEnabled(false);
  441. if (mat.diffuseTexture !== null) {
  442. this._promises.push(new Promise((resolve) => {
  443. (<Texture>mat.diffuseTexture).onLoadObservable.add(() => {
  444. pointsGroup._groupImageData = mat.diffuseTexture!.readPixels();
  445. pointsGroup._groupImgWidth = mat.diffuseTexture!._texture!.width;
  446. pointsGroup._groupImgHeight = mat.diffuseTexture!._texture!.height;
  447. this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true);
  448. clone.dispose();
  449. resolve();
  450. });
  451. }));
  452. }
  453. else {
  454. this._promises.push(new Promise((resolve) => {
  455. (<Texture>mat.emissiveTexture).onLoadObservable.add(() => {
  456. pointsGroup._groupImageData = mat.emissiveTexture!.readPixels();
  457. pointsGroup._groupImgWidth = mat.emissiveTexture!._texture!.width;
  458. pointsGroup._groupImgHeight = mat.emissiveTexture!._texture!.height;
  459. this._setPointsColorOrUV(clone, pointsGroup, isVolume, true);
  460. clone.dispose();
  461. resolve();
  462. });
  463. }));
  464. }
  465. }
  466. // calculates the point density per facet of a mesh for surface points
  467. private _calculateDensity(nbPoints: number, positions: FloatArray, indices: FloatArray): number[] {
  468. var density: number[] = new Array<number>();
  469. var index: number;
  470. var id0: number;
  471. var id1: number;
  472. var id2: number;
  473. var v0X: number;
  474. var v0Y: number;
  475. var v0Z: number;
  476. var v1X: number;
  477. var v1Y: number;
  478. var v1Z: number;
  479. var v2X: number;
  480. var v2Y: number;
  481. var v2Z: number;
  482. var vertex0 = Vector3.Zero();
  483. var vertex1 = Vector3.Zero();
  484. var vertex2 = Vector3.Zero();
  485. var vec0 = Vector3.Zero();
  486. var vec1 = Vector3.Zero();
  487. var vec2 = Vector3.Zero();
  488. var a: number; //length of side of triangle
  489. var b: number; //length of side of triangle
  490. var c: number; //length of side of triangle
  491. var p: number; //perimeter of triangle
  492. var area: number;
  493. var areas: number[] = new Array<number>();
  494. var surfaceArea: number = 0;
  495. var nbFacets = indices.length / 3;
  496. //surface area
  497. for (var index = 0; index < nbFacets; index++) {
  498. id0 = indices[3 * index];
  499. id1 = indices[3 * index + 1];
  500. id2 = indices[3 * index + 2];
  501. v0X = positions[3 * id0];
  502. v0Y = positions[3 * id0 + 1];
  503. v0Z = positions[3 * id0 + 2];
  504. v1X = positions[3 * id1];
  505. v1Y = positions[3 * id1 + 1];
  506. v1Z = positions[3 * id1 + 2];
  507. v2X = positions[3 * id2];
  508. v2Y = positions[3 * id2 + 1];
  509. v2Z = positions[3 * id2 + 2];
  510. vertex0.set(v0X, v0Y, v0Z);
  511. vertex1.set(v1X, v1Y, v1Z);
  512. vertex2.set(v2X, v2Y, v2Z);
  513. vertex1.subtractToRef(vertex0, vec0);
  514. vertex2.subtractToRef(vertex1, vec1);
  515. vertex2.subtractToRef(vertex0, vec2);
  516. a = vec0.length();
  517. b = vec1.length();
  518. c = vec2.length();
  519. p = (a + b + c) / 2;
  520. area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
  521. surfaceArea += area;
  522. areas[index] = area;
  523. }
  524. var pointCount: number = 0;
  525. for (var index = 0; index < nbFacets; index++) {
  526. density[index] = Math.floor(nbPoints * areas[index] / surfaceArea);
  527. pointCount += density[index];
  528. }
  529. var diff: number = nbPoints - pointCount;
  530. var pointsPerFacet: number = Math.floor(diff / nbFacets);
  531. var extraPoints: number = diff % nbFacets;
  532. if (pointsPerFacet > 0) {
  533. density = density.map((x) => x + pointsPerFacet);
  534. }
  535. for (var index = 0; index < extraPoints; index++) {
  536. density[index] += 1;
  537. }
  538. return density;
  539. }
  540. /**
  541. * Adds points to the PCS in random positions within a unit sphere
  542. * @param nb (positive integer) the number of particles to be created from this model
  543. * @param pointFunction is an optional javascript function to be called for each particle on PCS creation
  544. * @returns the number of groups in the system
  545. */
  546. public addPoints(nb: number, pointFunction: any = this._randomUnitVector): number {
  547. var pointsGroup = new PointsGroup(this._groupCounter, pointFunction);
  548. var cp: CloudPoint;
  549. // particles
  550. var idx = this.nbParticles;
  551. for (var i = 0; i < nb; i++) {
  552. cp = this._addParticle(idx, pointsGroup, this._groupCounter, i);
  553. if (pointsGroup && pointsGroup._positionFunction) {
  554. pointsGroup._positionFunction(cp, idx, i);
  555. }
  556. this._positions.push(cp.position.x, cp.position.y, cp.position.z);
  557. if (cp.color) {
  558. this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a);
  559. }
  560. idx++;
  561. }
  562. this.nbParticles += nb;
  563. this._groupCounter++;
  564. return this._groupCounter;
  565. }
  566. /**
  567. * Adds points to the PCS from the surface of the model shape
  568. * @param mesh is any Mesh object that will be used as a surface model for the points
  569. * @param nb (positive integer) the number of particles to be created from this model
  570. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)
  571. * @param color (color3) to be used when colorWith is stated
  572. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  573. * @returns the number of groups in the system
  574. */
  575. public addSurfacePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4, range?: number): number {
  576. var colored = colorWith ? colorWith : PointColor.RANDOM;
  577. if (isNaN(colored) || colored < 0 || colored > 3) {
  578. colored = PointColor.RANDOM ;
  579. }
  580. color = color ? color : new Color4(1, 1, 1, 1);
  581. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  582. var meshInd = <IndicesArray>mesh.getIndices();
  583. this._groups.push(this._groupCounter);
  584. var pointsGroup = new PointsGroup(this._groupCounter, null);
  585. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  586. switch (colored) {
  587. case PointColor.COLOR:
  588. this._colorFromTexture(mesh, pointsGroup, false);
  589. break;
  590. case PointColor.UV:
  591. this._setPointsColorOrUV(mesh, pointsGroup, false, false, false);
  592. break;
  593. case PointColor.RANDOM:
  594. this._setPointsColorOrUV(mesh, pointsGroup, false);
  595. break;
  596. case PointColor.STATED:
  597. this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, color, range);
  598. break;
  599. }
  600. this.nbParticles += nb;
  601. this._groupCounter++;
  602. return this._groupCounter - 1;
  603. }
  604. /**
  605. * Adds points to the PCS inside the model shape
  606. * @param mesh is any Mesh object that will be used as a surface model for the points
  607. * @param nb (positive integer) the number of particles to be created from this model
  608. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible),
  609. * @param color (color4) to be used when colorWith is stated
  610. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  611. * @returns the number of groups in the system
  612. */
  613. public addVolumePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4, range?: number): number {
  614. var colored = colorWith ? colorWith : PointColor.RANDOM;
  615. if (isNaN(colored) || colored < 0 || colored > 3) {
  616. colored = PointColor.RANDOM;
  617. }
  618. color = color ? color : new Color4(1, 1, 1, 1);
  619. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  620. var meshInd = <IndicesArray>mesh.getIndices();
  621. this._groups.push(this._groupCounter);
  622. var pointsGroup = new PointsGroup(this._groupCounter, null);
  623. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  624. switch (colored) {
  625. case PointColor.COLOR:
  626. this._colorFromTexture(mesh, pointsGroup, true);
  627. break;
  628. case PointColor.UV:
  629. this._setPointsColorOrUV(mesh, pointsGroup, true, false, false);
  630. break;
  631. case PointColor.RANDOM:
  632. this._setPointsColorOrUV(mesh, pointsGroup, true);
  633. break;
  634. case PointColor.STATED:
  635. this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, color, range);
  636. break;
  637. }
  638. this.nbParticles += nb;
  639. this._groupCounter++;
  640. return this._groupCounter - 1;
  641. }
  642. /**
  643. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  644. * This method calls `updateParticle()` for each particle of the SPS.
  645. * For an animated SPS, it is usually called within the render loop.
  646. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  647. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  648. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  649. * @returns the PCS.
  650. */
  651. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): PointsCloudSystem {
  652. if (!this._updatable || !this._isReady) {
  653. return this;
  654. }
  655. // custom beforeUpdate
  656. this.beforeUpdateParticles(start, end, update);
  657. const rotMatrix = TmpVectors.Matrix[0];
  658. const mesh = this.mesh;
  659. const colors32 = this._colors32;
  660. const positions32 = this._positions32;
  661. const uvs32 = this._uvs32;
  662. const tempVectors = TmpVectors.Vector3;
  663. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  664. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  665. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  666. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  667. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  668. Matrix.IdentityToRef(rotMatrix);
  669. var idx = 0; // current index of the particle
  670. if (this.mesh.isFacetDataEnabled) {
  671. this._computeBoundingBox = true;
  672. }
  673. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  674. if (this._computeBoundingBox) {
  675. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  676. const boundingInfo = this.mesh._boundingInfo;
  677. if (boundingInfo) {
  678. minimum.copyFrom(boundingInfo.minimum);
  679. maximum.copyFrom(boundingInfo.maximum);
  680. }
  681. }
  682. }
  683. var idx = 0; // particle index
  684. var pindex = 0; //index in positions array
  685. var cindex = 0; //index in color array
  686. var uindex = 0; //index in uv array
  687. // particle loop
  688. for (var p = start; p <= end; p++) {
  689. const particle = this.particles[p];
  690. idx = particle.idx;
  691. pindex = 3 * idx;
  692. cindex = 4 * idx;
  693. uindex = 2 * idx;
  694. // call to custom user function to update the particle properties
  695. this.updateParticle(particle);
  696. const particleRotationMatrix = particle._rotationMatrix;
  697. const particlePosition = particle.position;
  698. const particleGlobalPosition = particle._globalPosition;
  699. if (this._computeParticleRotation) {
  700. particle.getRotationMatrix(rotMatrix);
  701. }
  702. const particleHasParent = (particle.parentId !== null);
  703. if (particleHasParent) {
  704. const parent = this.particles[particle.parentId!];
  705. const parentRotationMatrix = parent._rotationMatrix;
  706. const parentGlobalPosition = parent._globalPosition;
  707. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  708. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  709. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  710. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  711. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  712. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  713. if (this._computeParticleRotation) {
  714. const rotMatrixValues = rotMatrix.m;
  715. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  716. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  717. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  718. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  719. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  720. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  721. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  722. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  723. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  724. }
  725. }
  726. else {
  727. particleGlobalPosition.x = 0;
  728. particleGlobalPosition.y = 0;
  729. particleGlobalPosition.z = 0;
  730. if (this._computeParticleRotation) {
  731. const rotMatrixValues = rotMatrix.m;
  732. particleRotationMatrix[0] = rotMatrixValues[0];
  733. particleRotationMatrix[1] = rotMatrixValues[1];
  734. particleRotationMatrix[2] = rotMatrixValues[2];
  735. particleRotationMatrix[3] = rotMatrixValues[4];
  736. particleRotationMatrix[4] = rotMatrixValues[5];
  737. particleRotationMatrix[5] = rotMatrixValues[6];
  738. particleRotationMatrix[6] = rotMatrixValues[8];
  739. particleRotationMatrix[7] = rotMatrixValues[9];
  740. particleRotationMatrix[8] = rotMatrixValues[10];
  741. }
  742. }
  743. const pivotBackTranslation = tempVectors[11];
  744. if (particle.translateFromPivot) {
  745. pivotBackTranslation.setAll(0.0);
  746. }
  747. else {
  748. pivotBackTranslation.copyFrom(particle.pivot);
  749. }
  750. // positions
  751. const tmpVertex = tempVectors[0];
  752. tmpVertex.copyFrom(particle.position);
  753. const vertexX = tmpVertex.x - particle.pivot.x;
  754. const vertexY = tmpVertex.y - particle.pivot.y;
  755. const vertexZ = tmpVertex.z - particle.pivot.z;
  756. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  757. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  758. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  759. rotatedX += pivotBackTranslation.x;
  760. rotatedY += pivotBackTranslation.y;
  761. rotatedZ += pivotBackTranslation.z;
  762. const px = positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  763. const py = positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  764. const pz = positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  765. if (this._computeBoundingBox) {
  766. minimum.minimizeInPlaceFromFloats(px, py, pz);
  767. maximum.maximizeInPlaceFromFloats(px, py, pz);
  768. }
  769. if (this._computeParticleColor && particle.color) {
  770. const color = particle.color;
  771. const colors32 = this._colors32;
  772. colors32[cindex] = color.r;
  773. colors32[cindex + 1] = color.g;
  774. colors32[cindex + 2] = color.b;
  775. colors32[cindex + 3] = color.a;
  776. }
  777. if (this._computeParticleTexture && particle.uv) {
  778. const uv = particle.uv;
  779. const uvs32 = this._uvs32;
  780. uvs32[uindex] = uv.x;
  781. uvs32[uindex + 1] = uv.y;
  782. }
  783. }
  784. // if the VBO must be updated
  785. if (update) {
  786. if (this._computeParticleColor) {
  787. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  788. }
  789. if (this._computeParticleTexture) {
  790. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  791. }
  792. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  793. }
  794. if (this._computeBoundingBox) {
  795. if (mesh._boundingInfo) {
  796. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  797. }
  798. else {
  799. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  800. }
  801. }
  802. this.afterUpdateParticles(start, end, update);
  803. return this;
  804. }
  805. /**
  806. * Disposes the PCS.
  807. */
  808. public dispose(): void {
  809. this.mesh.dispose();
  810. this.vars = null;
  811. // drop references to internal big arrays for the GC
  812. (<any>this._positions) = null;
  813. (<any>this._indices) = null;
  814. (<any>this._normals) = null;
  815. (<any>this._uvs) = null;
  816. (<any>this._colors) = null;
  817. (<any>this._indices32) = null;
  818. (<any>this._positions32) = null;
  819. (<any>this._uvs32) = null;
  820. (<any>this._colors32) = null;
  821. }
  822. /**
  823. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  824. * doc :
  825. * @returns the PCS.
  826. */
  827. public refreshVisibleSize(): PointsCloudSystem {
  828. if (!this._isVisibilityBoxLocked) {
  829. this.mesh.refreshBoundingInfo();
  830. }
  831. return this;
  832. }
  833. /**
  834. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  835. * @param size the size (float) of the visibility box
  836. * note : this doesn't lock the PCS mesh bounding box.
  837. * doc :
  838. */
  839. public setVisibilityBox(size: number): void {
  840. var vis = size / 2;
  841. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  842. }
  843. /**
  844. * Gets whether the PCS is always visible or not
  845. * doc :
  846. */
  847. public get isAlwaysVisible(): boolean {
  848. return this._alwaysVisible;
  849. }
  850. /**
  851. * Sets the PCS as always visible or not
  852. * doc :
  853. */
  854. public set isAlwaysVisible(val: boolean) {
  855. this._alwaysVisible = val;
  856. this.mesh.alwaysSelectAsActiveMesh = val;
  857. }
  858. /**
  859. * Tells to `setParticles()` to compute the particle rotations or not
  860. * Default value : false. The PCS is faster when it's set to false
  861. * Note : particle rotations are only applied to parent particles
  862. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate
  863. */
  864. public set computeParticleRotation(val: boolean) {
  865. this._computeParticleRotation = val;
  866. }
  867. /**
  868. * Tells to `setParticles()` to compute the particle colors or not.
  869. * Default value : true. The PCS is faster when it's set to false.
  870. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  871. */
  872. public set computeParticleColor(val: boolean) {
  873. this._computeParticleColor = val;
  874. }
  875. public set computeParticleTexture(val: boolean) {
  876. this._computeParticleTexture = val;
  877. }
  878. /**
  879. * Gets if `setParticles()` computes the particle colors or not.
  880. * Default value : false. The PCS is faster when it's set to false.
  881. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  882. */
  883. public get computeParticleColor(): boolean {
  884. return this._computeParticleColor;
  885. }
  886. /**
  887. * Gets if `setParticles()` computes the particle textures or not.
  888. * Default value : false. The PCS is faster when it's set to false.
  889. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  890. */
  891. public get computeParticleTexture(): boolean {
  892. return this._computeParticleTexture;
  893. }
  894. /**
  895. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  896. */
  897. public set computeBoundingBox(val: boolean) {
  898. this._computeBoundingBox = val;
  899. }
  900. /**
  901. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  902. */
  903. public get computeBoundingBox(): boolean {
  904. return this._computeBoundingBox;
  905. }
  906. // =======================================================================
  907. // Particle behavior logic
  908. // these following methods may be overwritten by users to fit their needs
  909. /**
  910. * This function does nothing. It may be overwritten to set all the particle first values.
  911. * The PCS doesn't call this function, you may have to call it by your own.
  912. * doc :
  913. */
  914. public initParticles(): void {
  915. }
  916. /**
  917. * This function does nothing. It may be overwritten to recycle a particle
  918. * The PCS doesn't call this function, you can to call it
  919. * doc :
  920. * @param particle The particle to recycle
  921. * @returns the recycled particle
  922. */
  923. public recycleParticle(particle: CloudPoint): CloudPoint {
  924. return particle;
  925. }
  926. /**
  927. * Updates a particle : this function should be overwritten by the user.
  928. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  929. * doc :
  930. * @example : just set a particle position or velocity and recycle conditions
  931. * @param particle The particle to update
  932. * @returns the updated particle
  933. */
  934. public updateParticle(particle: CloudPoint): CloudPoint {
  935. return particle;
  936. }
  937. /**
  938. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  939. * This does nothing and may be overwritten by the user.
  940. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  941. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  942. * @param update the boolean update value actually passed to setParticles()
  943. */
  944. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  945. }
  946. /**
  947. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  948. * This will be passed three parameters.
  949. * This does nothing and may be overwritten by the user.
  950. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  951. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  952. * @param update the boolean update value actually passed to setParticles()
  953. */
  954. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  955. }
  956. }