meshSimplification.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import { IndicesArray } from "types";
  2. import { Vector3, Epsilon } from "Math/math";
  3. import { VertexBuffer } from "Mesh/vertexBuffer";
  4. import { SubMesh } from "Mesh/subMesh";
  5. import { Mesh } from "Mesh/mesh";
  6. import { AsyncLoop } from "Tools/tools";
  7. /**
  8. * A simplifier interface for future simplification implementations
  9. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  10. */
  11. export interface ISimplifier {
  12. /**
  13. * Simplification of a given mesh according to the given settings.
  14. * Since this requires computation, it is assumed that the function runs async.
  15. * @param settings The settings of the simplification, including quality and distance
  16. * @param successCallback A callback that will be called after the mesh was simplified.
  17. * @param errorCallback in case of an error, this callback will be called. optional.
  18. */
  19. simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void;
  20. }
  21. /**
  22. * Expected simplification settings.
  23. * Quality should be between 0 and 1 (1 being 100%, 0 being 0%)
  24. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  25. */
  26. export interface ISimplificationSettings {
  27. /**
  28. * Gets or sets the expected quality
  29. */
  30. quality: number;
  31. /**
  32. * Gets or sets the distance when this optimized version should be used
  33. */
  34. distance: number;
  35. /**
  36. * Gets an already optimized mesh
  37. */
  38. optimizeMesh?: boolean;
  39. }
  40. /**
  41. * Class used to specify simplification options
  42. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  43. */
  44. export class SimplificationSettings implements ISimplificationSettings {
  45. /**
  46. * Creates a SimplificationSettings
  47. * @param quality expected quality
  48. * @param distance distance when this optimized version should be used
  49. * @param optimizeMesh already optimized mesh
  50. */
  51. constructor(
  52. /** expected quality */
  53. public quality: number,
  54. /** distance when this optimized version should be used */
  55. public distance: number,
  56. /** already optimized mesh */
  57. public optimizeMesh?: boolean) {
  58. }
  59. }
  60. /**
  61. * Interface used to define a simplification task
  62. */
  63. export interface ISimplificationTask {
  64. /**
  65. * Array of settings
  66. */
  67. settings: Array<ISimplificationSettings>;
  68. /**
  69. * Simplification type
  70. */
  71. simplificationType: SimplificationType;
  72. /**
  73. * Mesh to simplify
  74. */
  75. mesh: Mesh;
  76. /**
  77. * Callback called on success
  78. */
  79. successCallback?: () => void;
  80. /**
  81. * Defines if parallel processing can be used
  82. */
  83. parallelProcessing: boolean;
  84. }
  85. /**
  86. * Queue used to order the simplification tasks
  87. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  88. */
  89. export class SimplificationQueue {
  90. private _simplificationArray: Array<ISimplificationTask>;
  91. /**
  92. * Gets a boolean indicating that the process is still running
  93. */
  94. public running: boolean;
  95. /**
  96. * Creates a new queue
  97. */
  98. constructor() {
  99. this.running = false;
  100. this._simplificationArray = [];
  101. }
  102. /**
  103. * Adds a new simplification task
  104. * @param task defines a task to add
  105. */
  106. public addTask(task: ISimplificationTask) {
  107. this._simplificationArray.push(task);
  108. }
  109. /**
  110. * Execute next task
  111. */
  112. public executeNext() {
  113. var task = this._simplificationArray.pop();
  114. if (task) {
  115. this.running = true;
  116. this.runSimplification(task);
  117. } else {
  118. this.running = false;
  119. }
  120. }
  121. /**
  122. * Execute a simplification task
  123. * @param task defines the task to run
  124. */
  125. public runSimplification(task: ISimplificationTask) {
  126. if (task.parallelProcessing) {
  127. //parallel simplifier
  128. task.settings.forEach((setting) => {
  129. var simplifier = this.getSimplifier(task);
  130. simplifier.simplify(setting, (newMesh) => {
  131. task.mesh.addLODLevel(setting.distance, newMesh);
  132. newMesh.isVisible = true;
  133. //check if it is the last
  134. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  135. //all done, run the success callback.
  136. task.successCallback();
  137. }
  138. this.executeNext();
  139. });
  140. });
  141. } else {
  142. //single simplifier.
  143. var simplifier = this.getSimplifier(task);
  144. var runDecimation = (setting: ISimplificationSettings, callback: () => void) => {
  145. simplifier.simplify(setting, (newMesh) => {
  146. task.mesh.addLODLevel(setting.distance, newMesh);
  147. newMesh.isVisible = true;
  148. //run the next quality level
  149. callback();
  150. });
  151. };
  152. AsyncLoop.Run(task.settings.length, (loop: AsyncLoop) => {
  153. runDecimation(task.settings[loop.index], () => {
  154. loop.executeNext();
  155. });
  156. }, () => {
  157. //execution ended, run the success callback.
  158. if (task.successCallback) {
  159. task.successCallback();
  160. }
  161. this.executeNext();
  162. });
  163. }
  164. }
  165. private getSimplifier(task: ISimplificationTask): ISimplifier {
  166. switch (task.simplificationType) {
  167. case SimplificationType.QUADRATIC:
  168. default:
  169. return new QuadraticErrorSimplification(task.mesh);
  170. }
  171. }
  172. }
  173. /**
  174. * The implemented types of simplification
  175. * At the moment only Quadratic Error Decimation is implemented
  176. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  177. */
  178. export enum SimplificationType {
  179. /** Quadratic error decimation */
  180. QUADRATIC
  181. }
  182. class DecimationTriangle {
  183. public normal: Vector3;
  184. public error: Array<number>;
  185. public deleted: boolean;
  186. public isDirty: boolean;
  187. public borderFactor: number;
  188. public deletePending: boolean;
  189. public originalOffset: number;
  190. constructor(public vertices: Array<DecimationVertex>) {
  191. this.error = new Array<number>(4);
  192. this.deleted = false;
  193. this.isDirty = false;
  194. this.deletePending = false;
  195. this.borderFactor = 0;
  196. }
  197. }
  198. class DecimationVertex {
  199. public q: QuadraticMatrix;
  200. public isBorder: boolean;
  201. public triangleStart: number;
  202. public triangleCount: number;
  203. public originalOffsets: Array<number>;
  204. constructor(public position: Vector3, public id: number) {
  205. this.isBorder = true;
  206. this.q = new QuadraticMatrix();
  207. this.triangleCount = 0;
  208. this.triangleStart = 0;
  209. this.originalOffsets = [];
  210. }
  211. public updatePosition(newPosition: Vector3) {
  212. this.position.copyFrom(newPosition);
  213. }
  214. }
  215. class QuadraticMatrix {
  216. public data: Array<number>;
  217. constructor(data?: Array<number>) {
  218. this.data = new Array(10);
  219. for (var i = 0; i < 10; ++i) {
  220. if (data && data[i]) {
  221. this.data[i] = data[i];
  222. } else {
  223. this.data[i] = 0;
  224. }
  225. }
  226. }
  227. public det(a11: number, a12: number, a13: number, a21: number, a22: number, a23: number, a31: number, a32: number, a33: number): number {
  228. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  229. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  230. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  231. return det;
  232. }
  233. public addInPlace(matrix: QuadraticMatrix) {
  234. for (var i = 0; i < 10; ++i) {
  235. this.data[i] += matrix.data[i];
  236. }
  237. }
  238. public addArrayInPlace(data: Array<number>) {
  239. for (var i = 0; i < 10; ++i) {
  240. this.data[i] += data[i];
  241. }
  242. }
  243. public add(matrix: QuadraticMatrix): QuadraticMatrix {
  244. var m = new QuadraticMatrix();
  245. for (var i = 0; i < 10; ++i) {
  246. m.data[i] = this.data[i] + matrix.data[i];
  247. }
  248. return m;
  249. }
  250. public static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix {
  251. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  252. }
  253. //returning an array to avoid garbage collection
  254. public static DataFromNumbers(a: number, b: number, c: number, d: number) {
  255. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  256. }
  257. }
  258. class Reference {
  259. constructor(public vertexId: number, public triangleId: number) { }
  260. }
  261. /**
  262. * An implementation of the Quadratic Error simplification algorithm.
  263. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  264. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  265. * @author RaananW
  266. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  267. */
  268. class QuadraticErrorSimplification implements ISimplifier {
  269. private triangles: Array<DecimationTriangle>;
  270. private vertices: Array<DecimationVertex>;
  271. private references: Array<Reference>;
  272. private _reconstructedMesh: Mesh;
  273. public syncIterations = 5000;
  274. public aggressiveness: number;
  275. public decimationIterations: number;
  276. public boundingBoxEpsilon: number;
  277. constructor(private _mesh: Mesh) {
  278. this.aggressiveness = 7;
  279. this.decimationIterations = 100;
  280. this.boundingBoxEpsilon = Epsilon;
  281. }
  282. public simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void) {
  283. this.initDecimatedMesh();
  284. //iterating through the submeshes array, one after the other.
  285. AsyncLoop.Run(this._mesh.subMeshes.length, (loop: AsyncLoop) => {
  286. this.initWithMesh(loop.index, () => {
  287. this.runDecimation(settings, loop.index, () => {
  288. loop.executeNext();
  289. });
  290. }, settings.optimizeMesh);
  291. }, () => {
  292. setTimeout(() => {
  293. successCallback(this._reconstructedMesh);
  294. }, 0);
  295. });
  296. }
  297. private runDecimation(settings: ISimplificationSettings, submeshIndex: number, successCallback: () => void) {
  298. var targetCount = ~~(this.triangles.length * settings.quality);
  299. var deletedTriangles = 0;
  300. var triangleCount = this.triangles.length;
  301. var iterationFunction = (iteration: number, callback: () => void) => {
  302. setTimeout(() => {
  303. if (iteration % 5 === 0) {
  304. this.updateMesh(iteration === 0);
  305. }
  306. for (var i = 0; i < this.triangles.length; ++i) {
  307. this.triangles[i].isDirty = false;
  308. }
  309. var threshold = 0.000000001 * Math.pow((iteration + 3), this.aggressiveness);
  310. var trianglesIterator = (i: number) => {
  311. var tIdx = ~~(((this.triangles.length / 2) + i) % this.triangles.length);
  312. var t = this.triangles[tIdx];
  313. if (!t) { return; }
  314. if (t.error[3] > threshold || t.deleted || t.isDirty) { return; }
  315. for (var j = 0; j < 3; ++j) {
  316. if (t.error[j] < threshold) {
  317. var deleted0: Array<boolean> = [];
  318. var deleted1: Array<boolean> = [];
  319. var v0 = t.vertices[j];
  320. var v1 = t.vertices[(j + 1) % 3];
  321. if (v0.isBorder || v1.isBorder) { continue; }
  322. var p = Vector3.Zero();
  323. // var n = Vector3.Zero();
  324. // var uv = Vector2.Zero();
  325. // var color = new Color4(0, 0, 0, 1);
  326. this.calculateError(v0, v1, p);
  327. var delTr = new Array<DecimationTriangle>();
  328. if (this.isFlipped(v0, v1, p, deleted0, delTr)) { continue; }
  329. if (this.isFlipped(v1, v0, p, deleted1, delTr)) { continue; }
  330. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  331. continue;
  332. }
  333. var uniqueArray = new Array<DecimationTriangle>();
  334. delTr.forEach((deletedT) => {
  335. if (uniqueArray.indexOf(deletedT) === -1) {
  336. deletedT.deletePending = true;
  337. uniqueArray.push(deletedT);
  338. }
  339. });
  340. if (uniqueArray.length % 2 !== 0) {
  341. continue;
  342. }
  343. v0.q = v1.q.add(v0.q);
  344. v0.updatePosition(p);
  345. var tStart = this.references.length;
  346. deletedTriangles = this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  347. deletedTriangles = this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  348. var tCount = this.references.length - tStart;
  349. if (tCount <= v0.triangleCount) {
  350. if (tCount) {
  351. for (var c = 0; c < tCount; c++) {
  352. this.references[v0.triangleStart + c] = this.references[tStart + c];
  353. }
  354. }
  355. } else {
  356. v0.triangleStart = tStart;
  357. }
  358. v0.triangleCount = tCount;
  359. break;
  360. }
  361. }
  362. };
  363. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback, () => { return (triangleCount - deletedTriangles <= targetCount); });
  364. }, 0);
  365. };
  366. AsyncLoop.Run(this.decimationIterations, (loop: AsyncLoop) => {
  367. if (triangleCount - deletedTriangles <= targetCount) { loop.breakLoop(); }
  368. else {
  369. iterationFunction(loop.index, () => {
  370. loop.executeNext();
  371. });
  372. }
  373. }, () => {
  374. setTimeout(() => {
  375. //reconstruct this part of the mesh
  376. this.reconstructMesh(submeshIndex);
  377. successCallback();
  378. }, 0);
  379. });
  380. }
  381. private initWithMesh(submeshIndex: number, callback: Function, optimizeMesh?: boolean) {
  382. this.vertices = [];
  383. this.triangles = [];
  384. var positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);
  385. var indices = this._mesh.getIndices();
  386. var submesh = this._mesh.subMeshes[submeshIndex];
  387. var findInVertices = (positionToSearch: Vector3) => {
  388. if (optimizeMesh) {
  389. for (var ii = 0; ii < this.vertices.length; ++ii) {
  390. if (this.vertices[ii].position.equals(positionToSearch)) {
  391. return this.vertices[ii];
  392. }
  393. }
  394. }
  395. return null;
  396. };
  397. var vertexReferences: Array<number> = [];
  398. var vertexInit = (i: number) => {
  399. if (!positionData) {
  400. return;
  401. }
  402. var offset = i + submesh.verticesStart;
  403. var position = Vector3.FromArray(positionData, offset * 3);
  404. var vertex = findInVertices(position) || new DecimationVertex(position, this.vertices.length);
  405. vertex.originalOffsets.push(offset);
  406. if (vertex.id === this.vertices.length) {
  407. this.vertices.push(vertex);
  408. }
  409. vertexReferences.push(vertex.id);
  410. };
  411. //var totalVertices = mesh.getTotalVertices();
  412. var totalVertices = submesh.verticesCount;
  413. AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => {
  414. var indicesInit = (i: number) => {
  415. if (!indices) {
  416. return;
  417. }
  418. var offset = (submesh.indexStart / 3) + i;
  419. var pos = (offset * 3);
  420. var i0 = indices[pos + 0];
  421. var i1 = indices[pos + 1];
  422. var i2 = indices[pos + 2];
  423. var v0: DecimationVertex = this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  424. var v1: DecimationVertex = this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  425. var v2: DecimationVertex = this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  426. var triangle = new DecimationTriangle([v0, v1, v2]);
  427. triangle.originalOffset = pos;
  428. this.triangles.push(triangle);
  429. };
  430. AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => {
  431. this.init(callback);
  432. });
  433. });
  434. }
  435. private init(callback: Function) {
  436. var triangleInit1 = (i: number) => {
  437. var t = this.triangles[i];
  438. t.normal = Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  439. for (var j = 0; j < 3; j++) {
  440. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(Vector3.Dot(t.normal, t.vertices[0].position))));
  441. }
  442. };
  443. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, () => {
  444. var triangleInit2 = (i: number) => {
  445. var t = this.triangles[i];
  446. for (var j = 0; j < 3; ++j) {
  447. t.error[j] = this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  448. }
  449. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  450. };
  451. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2, () => {
  452. callback();
  453. });
  454. });
  455. }
  456. private reconstructMesh(submeshIndex: number) {
  457. var newTriangles: Array<DecimationTriangle> = [];
  458. var i: number;
  459. for (i = 0; i < this.vertices.length; ++i) {
  460. this.vertices[i].triangleCount = 0;
  461. }
  462. var t: DecimationTriangle;
  463. var j: number;
  464. for (i = 0; i < this.triangles.length; ++i) {
  465. if (!this.triangles[i].deleted) {
  466. t = this.triangles[i];
  467. for (j = 0; j < 3; ++j) {
  468. t.vertices[j].triangleCount = 1;
  469. }
  470. newTriangles.push(t);
  471. }
  472. }
  473. var newPositionData = <number[]>(this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || []);
  474. var newNormalData = <number[]>(this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || []);
  475. var newUVsData = <number[]>(this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || []);
  476. var newColorsData = <number[]>(this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || []);
  477. var normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);
  478. var uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);
  479. var colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind);
  480. var vertexCount = 0;
  481. for (i = 0; i < this.vertices.length; ++i) {
  482. var vertex = this.vertices[i];
  483. vertex.id = vertexCount;
  484. if (vertex.triangleCount) {
  485. vertex.originalOffsets.forEach((originalOffset) => {
  486. if (!normalData) {
  487. return;
  488. }
  489. newPositionData.push(vertex.position.x);
  490. newPositionData.push(vertex.position.y);
  491. newPositionData.push(vertex.position.z);
  492. newNormalData.push(normalData[originalOffset * 3]);
  493. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  494. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  495. if (uvs && uvs.length) {
  496. newUVsData.push(uvs[(originalOffset * 2)]);
  497. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  498. } else if (colorsData && colorsData.length) {
  499. newColorsData.push(colorsData[(originalOffset * 4)]);
  500. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  501. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  502. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  503. }
  504. ++vertexCount;
  505. });
  506. }
  507. }
  508. var startingIndex = this._reconstructedMesh.getTotalIndices();
  509. var startingVertex = this._reconstructedMesh.getTotalVertices();
  510. var submeshesArray = this._reconstructedMesh.subMeshes;
  511. this._reconstructedMesh.subMeshes = [];
  512. var newIndicesArray: number[] = <number[]>this._reconstructedMesh.getIndices(); //[];
  513. var originalIndices = <IndicesArray>this._mesh.getIndices();
  514. for (i = 0; i < newTriangles.length; ++i) {
  515. t = newTriangles[i]; //now get the new referencing point for each vertex
  516. [0, 1, 2].forEach((idx) => {
  517. var id = originalIndices[t.originalOffset + idx];
  518. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  519. if (offset < 0) { offset = 0; }
  520. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  521. });
  522. }
  523. //overwriting the old vertex buffers and indices.
  524. this._reconstructedMesh.setIndices(newIndicesArray);
  525. this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);
  526. this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);
  527. if (newUVsData.length > 0) {
  528. this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);
  529. }
  530. if (newColorsData.length > 0) {
  531. this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);
  532. }
  533. //create submesh
  534. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  535. if (submeshIndex > 0) {
  536. this._reconstructedMesh.subMeshes = [];
  537. submeshesArray.forEach((submesh) => {
  538. SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */submesh.indexStart, submesh.indexCount, submesh.getMesh());
  539. });
  540. SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  541. }
  542. }
  543. private initDecimatedMesh() {
  544. this._reconstructedMesh = new Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  545. this._reconstructedMesh.material = this._mesh.material;
  546. this._reconstructedMesh.parent = this._mesh.parent;
  547. this._reconstructedMesh.isVisible = false;
  548. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  549. }
  550. private isFlipped(vertex1: DecimationVertex, vertex2: DecimationVertex, point: Vector3, deletedArray: Array<boolean>, delTr: Array<DecimationTriangle>): boolean {
  551. for (var i = 0; i < vertex1.triangleCount; ++i) {
  552. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  553. if (t.deleted) { continue; }
  554. var s = this.references[vertex1.triangleStart + i].vertexId;
  555. var v1 = t.vertices[(s + 1) % 3];
  556. var v2 = t.vertices[(s + 2) % 3];
  557. if ((v1 === vertex2 || v2 === vertex2)) {
  558. deletedArray[i] = true;
  559. delTr.push(t);
  560. continue;
  561. }
  562. var d1 = v1.position.subtract(point);
  563. d1 = d1.normalize();
  564. var d2 = v2.position.subtract(point);
  565. d2 = d2.normalize();
  566. if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) { return true; }
  567. var normal = Vector3.Cross(d1, d2).normalize();
  568. deletedArray[i] = false;
  569. if (Vector3.Dot(normal, t.normal) < 0.2) { return true; }
  570. }
  571. return false;
  572. }
  573. private updateTriangles(origVertex: DecimationVertex, vertex: DecimationVertex, deletedArray: Array<boolean>, deletedTriangles: number): number {
  574. var newDeleted = deletedTriangles;
  575. for (var i = 0; i < vertex.triangleCount; ++i) {
  576. var ref = this.references[vertex.triangleStart + i];
  577. var t = this.triangles[ref.triangleId];
  578. if (t.deleted) { continue; }
  579. if (deletedArray[i] && t.deletePending) {
  580. t.deleted = true;
  581. newDeleted++;
  582. continue;
  583. }
  584. t.vertices[ref.vertexId] = origVertex;
  585. t.isDirty = true;
  586. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  587. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  588. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  589. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  590. this.references.push(ref);
  591. }
  592. return newDeleted;
  593. }
  594. private identifyBorder() {
  595. for (var i = 0; i < this.vertices.length; ++i) {
  596. var vCount: Array<number> = [];
  597. var vId: Array<number> = [];
  598. var v = this.vertices[i];
  599. var j: number;
  600. for (j = 0; j < v.triangleCount; ++j) {
  601. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  602. for (var ii = 0; ii < 3; ii++) {
  603. var ofs = 0;
  604. var vv = triangle.vertices[ii];
  605. while (ofs < vCount.length) {
  606. if (vId[ofs] === vv.id) { break; }
  607. ++ofs;
  608. }
  609. if (ofs === vCount.length) {
  610. vCount.push(1);
  611. vId.push(vv.id);
  612. } else {
  613. vCount[ofs]++;
  614. }
  615. }
  616. }
  617. for (j = 0; j < vCount.length; ++j) {
  618. if (vCount[j] === 1) {
  619. this.vertices[vId[j]].isBorder = true;
  620. } else {
  621. this.vertices[vId[j]].isBorder = false;
  622. }
  623. }
  624. }
  625. }
  626. private updateMesh(identifyBorders: boolean = false) {
  627. var i: number;
  628. if (!identifyBorders) {
  629. var newTrianglesVector: Array<DecimationTriangle> = [];
  630. for (i = 0; i < this.triangles.length; ++i) {
  631. if (!this.triangles[i].deleted) {
  632. newTrianglesVector.push(this.triangles[i]);
  633. }
  634. }
  635. this.triangles = newTrianglesVector;
  636. }
  637. for (i = 0; i < this.vertices.length; ++i) {
  638. this.vertices[i].triangleCount = 0;
  639. this.vertices[i].triangleStart = 0;
  640. }
  641. var t: DecimationTriangle;
  642. var j: number;
  643. var v: DecimationVertex;
  644. for (i = 0; i < this.triangles.length; ++i) {
  645. t = this.triangles[i];
  646. for (j = 0; j < 3; ++j) {
  647. v = t.vertices[j];
  648. v.triangleCount++;
  649. }
  650. }
  651. var tStart = 0;
  652. for (i = 0; i < this.vertices.length; ++i) {
  653. this.vertices[i].triangleStart = tStart;
  654. tStart += this.vertices[i].triangleCount;
  655. this.vertices[i].triangleCount = 0;
  656. }
  657. var newReferences: Array<Reference> = new Array(this.triangles.length * 3);
  658. for (i = 0; i < this.triangles.length; ++i) {
  659. t = this.triangles[i];
  660. for (j = 0; j < 3; ++j) {
  661. v = t.vertices[j];
  662. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  663. v.triangleCount++;
  664. }
  665. }
  666. this.references = newReferences;
  667. if (identifyBorders) {
  668. this.identifyBorder();
  669. }
  670. }
  671. private vertexError(q: QuadraticMatrix, point: Vector3): number {
  672. var x = point.x;
  673. var y = point.y;
  674. var z = point.z;
  675. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  676. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  677. }
  678. private calculateError(vertex1: DecimationVertex, vertex2: DecimationVertex, pointResult?: Vector3): number {
  679. var q = vertex1.q.add(vertex2.q);
  680. var border = vertex1.isBorder && vertex2.isBorder;
  681. var error: number = 0;
  682. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  683. if (qDet !== 0 && !border) {
  684. if (!pointResult) {
  685. pointResult = Vector3.Zero();
  686. }
  687. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  688. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  689. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  690. error = this.vertexError(q, pointResult);
  691. } else {
  692. var p3 = (vertex1.position.add(vertex2.position)).divide(new Vector3(2, 2, 2));
  693. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  694. var error1 = this.vertexError(q, vertex1.position);
  695. var error2 = this.vertexError(q, vertex2.position);
  696. var error3 = this.vertexError(q, p3);
  697. error = Math.min(error1, error2, error3);
  698. if (error === error1) {
  699. if (pointResult) {
  700. pointResult.copyFrom(vertex1.position);
  701. }
  702. } else if (error === error2) {
  703. if (pointResult) {
  704. pointResult.copyFrom(vertex2.position);
  705. }
  706. } else {
  707. if (pointResult) {
  708. pointResult.copyFrom(p3);
  709. }
  710. }
  711. }
  712. return error;
  713. }
  714. }