pointsCloudSystem.js 44 KB

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