babylon.meshSimplification.ts 32 KB

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