babylon.meshSimplification.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. constructor(public vertices: Array<number>) {
  116. this.error = new Array<number>(4);
  117. this.deleted = false;
  118. this.isDirty = false;
  119. this.deletePending = false;
  120. this.borderFactor = 0;
  121. }
  122. }
  123. export class DecimationVertex {
  124. public q: QuadraticMatrix;
  125. public isBorder: boolean;
  126. public triangleStart: number;
  127. public triangleCount: number;
  128. //if color is present instead of uvs.
  129. public color: Color4;
  130. constructor(public position: Vector3, public normal: Vector3, public uv: Vector2, public id) {
  131. this.isBorder = true;
  132. this.q = new QuadraticMatrix();
  133. this.triangleCount = 0;
  134. this.triangleStart = 0;
  135. }
  136. }
  137. export class QuadraticMatrix {
  138. public data: Array<number>;
  139. constructor(data?: Array<number>) {
  140. this.data = new Array(10);
  141. for (var i = 0; i < 10; ++i) {
  142. if (data && data[i]) {
  143. this.data[i] = data[i];
  144. } else {
  145. this.data[i] = 0;
  146. }
  147. }
  148. }
  149. public det(a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  150. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  151. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  152. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  153. return det;
  154. }
  155. public addInPlace(matrix: QuadraticMatrix) {
  156. for (var i = 0; i < 10; ++i) {
  157. this.data[i] += matrix.data[i];
  158. }
  159. }
  160. public addArrayInPlace(data: Array<number>) {
  161. for (var i = 0; i < 10; ++i) {
  162. this.data[i] += data[i];
  163. }
  164. }
  165. public add(matrix: QuadraticMatrix): QuadraticMatrix {
  166. var m = new QuadraticMatrix();
  167. for (var i = 0; i < 10; ++i) {
  168. m.data[i] = this.data[i] + matrix.data[i];
  169. }
  170. return m;
  171. }
  172. public static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix {
  173. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  174. }
  175. //returning an array to avoid garbage collection
  176. public static DataFromNumbers(a: number, b: number, c: number, d: number) {
  177. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  178. }
  179. }
  180. export class Reference {
  181. constructor(public vertexId: number, public triangleId: number) { }
  182. }
  183. /**
  184. * An implementation of the Quadratic Error simplification algorithm.
  185. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  186. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  187. * @author RaananW
  188. */
  189. export class QuadraticErrorSimplification implements ISimplifier {
  190. private triangles: Array<DecimationTriangle>;
  191. private vertices: Array<DecimationVertex>;
  192. private references: Array<Reference>;
  193. private initialised: boolean = false;
  194. private _reconstructedMesh: Mesh;
  195. public syncIterations = 5000;
  196. public aggressiveness: number;
  197. public decimationIterations: number;
  198. public boundingBoxEpsilon: number;
  199. constructor(private _mesh: Mesh) {
  200. this.aggressiveness = 7;
  201. this.decimationIterations = 100;
  202. this.boundingBoxEpsilon = Engine.Epsilon;
  203. }
  204. public simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void) {
  205. this.initDecimatedMesh();
  206. //iterating through the submeshes array, one after the other.
  207. AsyncLoop.Run(this._mesh.subMeshes.length,(loop: AsyncLoop) => {
  208. this.initWithMesh(this._mesh, loop.index,() => {
  209. this.runDecimation(settings, loop.index,() => {
  210. loop.executeNext();
  211. });
  212. });
  213. },() => {
  214. setTimeout(() => {
  215. successCallback(this._reconstructedMesh);
  216. }, 0);
  217. });
  218. }
  219. private isTriangleOnBoundingBox(triangle: DecimationTriangle): boolean {
  220. var gCount = 0;
  221. triangle.vertices.forEach((vId) => {
  222. var count = 0;
  223. var vPos = this.vertices[vId].position;
  224. var bbox = this._mesh.getBoundingInfo().boundingBox;
  225. if (bbox.maximum.x - vPos.x < this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > this.boundingBoxEpsilon)
  226. ++count;
  227. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  228. ++count;
  229. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  230. ++count;
  231. if (count > 1) {
  232. ++gCount;
  233. };
  234. });
  235. if (gCount > 1) {
  236. console.log(triangle, gCount);
  237. }
  238. return gCount > 1;
  239. }
  240. private runDecimation(settings: ISimplificationSettings, submeshIndex: number, successCallback: () => void) {
  241. var targetCount = ~~(this.triangles.length * settings.quality);
  242. var deletedTriangles = 0;
  243. var triangleCount = this.triangles.length;
  244. var iterationFunction = (iteration: number, callback) => {
  245. setTimeout(() => {
  246. if (iteration % 5 === 0) {
  247. this.updateMesh(iteration === 0);
  248. }
  249. for (var i = 0; i < this.triangles.length; ++i) {
  250. this.triangles[i].isDirty = false;
  251. }
  252. var threshold = 0.000000001 * Math.pow((iteration + 3), this.aggressiveness);
  253. var trianglesIterator = (i) => {
  254. var tIdx = ~~(((this.triangles.length / 2) + i) % this.triangles.length);
  255. var t = this.triangles[tIdx];
  256. if (!t) return;
  257. if (t.error[3] > threshold || t.deleted || t.isDirty) { return }
  258. for (var j = 0; j < 3; ++j) {
  259. if (t.error[j] < threshold) {
  260. var deleted0: Array<boolean> = [];
  261. var deleted1: Array<boolean> = [];
  262. var i0 = t.vertices[j];
  263. var i1 = t.vertices[(j + 1) % 3];
  264. var v0 = this.vertices[i0];
  265. var v1 = this.vertices[i1];
  266. if (v0.isBorder !== v1.isBorder) continue;
  267. var p = Vector3.Zero();
  268. var n = Vector3.Zero();
  269. var uv = Vector2.Zero();
  270. var color = new Color4(0, 0, 0, 1);
  271. this.calculateError(v0, v1, p, n, uv, color);
  272. var delTr = [];
  273. if (this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr)) continue;
  274. if (this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr)) continue;
  275. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  276. continue;
  277. var uniqueArray = [];
  278. delTr.forEach(function (deletedT) {
  279. if (uniqueArray.indexOf(deletedT) === -1) {
  280. deletedT.deletePending = true;
  281. uniqueArray.push(deletedT);
  282. }
  283. });
  284. if (uniqueArray.length % 2 != 0) {
  285. continue;
  286. }
  287. v0.normal = n;
  288. if (v0.uv)
  289. v0.uv = uv;
  290. else if (v0.color)
  291. v0.color = color;
  292. v0.q = v1.q.add(v0.q);
  293. v0.position = p;
  294. var tStart = this.references.length;
  295. deletedTriangles = this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  296. deletedTriangles = this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  297. var tCount = this.references.length - tStart;
  298. if (tCount <= v0.triangleCount) {
  299. if (tCount) {
  300. for (var c = 0; c < tCount; c++) {
  301. this.references[v0.triangleStart + c] = this.references[tStart + c];
  302. }
  303. }
  304. } else {
  305. v0.triangleStart = tStart;
  306. }
  307. v0.triangleCount = tCount;
  308. break;
  309. }
  310. }
  311. };
  312. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback,() => { return (triangleCount - deletedTriangles <= targetCount) });
  313. }, 0);
  314. };
  315. AsyncLoop.Run(this.decimationIterations,(loop: AsyncLoop) => {
  316. if (triangleCount - deletedTriangles <= targetCount) loop.breakLoop();
  317. else {
  318. iterationFunction(loop.index,() => {
  319. loop.executeNext();
  320. });
  321. }
  322. },() => {
  323. setTimeout(() => {
  324. //reconstruct this part of the mesh
  325. this.reconstructMesh(submeshIndex);
  326. successCallback();
  327. }, 0);
  328. });
  329. }
  330. private initWithMesh(mesh: Mesh, submeshIndex: number, callback: Function) {
  331. if (!mesh) return;
  332. this.vertices = [];
  333. this.triangles = [];
  334. this._mesh = mesh;
  335. //It is assumed that a mesh has positions, normals and either uvs or colors.
  336. var positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);
  337. var normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);
  338. var uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);
  339. var colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind);
  340. var indices = mesh.getIndices();
  341. var submesh = mesh.subMeshes[submeshIndex];
  342. var vertexInit = (i) => {
  343. var offset = i + submesh.verticesStart;
  344. var vertex = new DecimationVertex(Vector3.FromArray(positionData, offset * 3), Vector3.FromArray(normalData, offset * 3), null, i);
  345. if (this._mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  346. vertex.uv = Vector2.FromArray(uvs, offset * 2);
  347. } else if (this._mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  348. vertex.color = Color4.FromArray(colorsData, offset * 4);
  349. }
  350. this.vertices.push(vertex);
  351. };
  352. //var totalVertices = mesh.getTotalVertices();
  353. var totalVertices = submesh.verticesCount;
  354. AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit,() => {
  355. var indicesInit = (i) => {
  356. var offset = (submesh.indexStart / 3) + i;
  357. var pos = (offset * 3);
  358. var i0 = indices[pos + 0] - submesh.verticesStart;
  359. var i1 = indices[pos + 1] - submesh.verticesStart;
  360. var i2 = indices[pos + 2] - submesh.verticesStart;
  361. var triangle = new DecimationTriangle([this.vertices[i0].id, this.vertices[i1].id, this.vertices[i2].id]);
  362. this.triangles.push(triangle);
  363. };
  364. AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit,() => {
  365. this.init(callback);
  366. });
  367. });
  368. }
  369. private init(callback: Function) {
  370. var triangleInit1 = (i) => {
  371. var t = this.triangles[i];
  372. t.normal = Vector3.Cross(this.vertices[t.vertices[1]].position.subtract(this.vertices[t.vertices[0]].position), this.vertices[t.vertices[2]].position.subtract(this.vertices[t.vertices[0]].position)).normalize();
  373. for (var j = 0; j < 3; j++) {
  374. this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(Vector3.Dot(t.normal, this.vertices[t.vertices[0]].position))));
  375. }
  376. };
  377. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1,() => {
  378. var triangleInit2 = (i) => {
  379. var t = this.triangles[i];
  380. for (var j = 0; j < 3; ++j) {
  381. t.error[j] = this.calculateError(this.vertices[t.vertices[j]], this.vertices[t.vertices[(j + 1) % 3]]);
  382. }
  383. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  384. };
  385. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2,() => {
  386. this.initialised = true;
  387. callback();
  388. });
  389. });
  390. }
  391. private reconstructMesh(submeshIndex: number) {
  392. var newTriangles: Array<DecimationTriangle> = [];
  393. var i: number;
  394. for (i = 0; i < this.vertices.length; ++i) {
  395. this.vertices[i].triangleCount = 0;
  396. }
  397. var t: DecimationTriangle;
  398. var j: number;
  399. for (i = 0; i < this.triangles.length; ++i) {
  400. if (!this.triangles[i].deleted) {
  401. t = this.triangles[i];
  402. for (j = 0; j < 3; ++j) {
  403. this.vertices[t.vertices[j]].triangleCount = 1;
  404. }
  405. newTriangles.push(t);
  406. }
  407. }
  408. var newVerticesOrder = [];
  409. //compact vertices, get the IDs of the vertices used.
  410. var dst = 0;
  411. for (i = 0; i < this.vertices.length; ++i) {
  412. if (this.vertices[i].triangleCount) {
  413. this.vertices[i].triangleStart = dst;
  414. this.vertices[dst].position = this.vertices[i].position;
  415. this.vertices[dst].normal = this.vertices[i].normal;
  416. this.vertices[dst].uv = this.vertices[i].uv;
  417. this.vertices[dst].color = this.vertices[i].color;
  418. newVerticesOrder.push(dst);
  419. dst++;
  420. }
  421. }
  422. for (i = 0; i < newTriangles.length; ++i) {
  423. t = newTriangles[i];
  424. for (j = 0; j < 3; ++j) {
  425. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  426. }
  427. }
  428. this.vertices = this.vertices.slice(0, dst);
  429. var newPositionData = this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || [];
  430. var newNormalData = this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || [];
  431. var newUVsData = this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || [];
  432. var newColorsData = this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || [];
  433. for (i = 0; i < newVerticesOrder.length; ++i) {
  434. newPositionData.push(this.vertices[i].position.x);
  435. newPositionData.push(this.vertices[i].position.y);
  436. newPositionData.push(this.vertices[i].position.z);
  437. newNormalData.push(this.vertices[i].normal.x);
  438. newNormalData.push(this.vertices[i].normal.y);
  439. newNormalData.push(this.vertices[i].normal.z);
  440. if (this.vertices[i].uv) {
  441. newUVsData.push(this.vertices[i].uv.x);
  442. newUVsData.push(this.vertices[i].uv.y);
  443. } else if (this.vertices[i].color) {
  444. newColorsData.push(this.vertices[i].color.r);
  445. newColorsData.push(this.vertices[i].color.g);
  446. newColorsData.push(this.vertices[i].color.b);
  447. newColorsData.push(this.vertices[i].color.a);
  448. }
  449. }
  450. var startingIndex = this._reconstructedMesh.getTotalIndices();
  451. var startingVertex = this._reconstructedMesh.getTotalVertices();
  452. var submeshesArray = this._reconstructedMesh.subMeshes;
  453. this._reconstructedMesh.subMeshes = [];
  454. var newIndicesArray: Array<number> = this._reconstructedMesh.getIndices(); //[];
  455. for (i = 0; i < newTriangles.length; ++i) {
  456. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  457. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  458. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  459. }
  460. //overwriting the old vertex buffers and indices.
  461. this._reconstructedMesh.setIndices(newIndicesArray);
  462. this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);
  463. this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);
  464. if (newUVsData.length > 0)
  465. this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);
  466. if (newColorsData.length > 0)
  467. this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);
  468. //create submesh
  469. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  470. if (submeshIndex > 0) {
  471. this._reconstructedMesh.subMeshes = [];
  472. submeshesArray.forEach(function (submesh) {
  473. new SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount,/* 0, newPositionData.length/3, */submesh.indexStart, submesh.indexCount, submesh.getMesh());
  474. });
  475. var newSubmesh = new SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length,/* 0, newPositionData.length / 3, */startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  476. }
  477. }
  478. private initDecimatedMesh() {
  479. this._reconstructedMesh = new Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  480. this._reconstructedMesh.material = this._mesh.material;
  481. this._reconstructedMesh.parent = this._mesh.parent;
  482. this._reconstructedMesh.isVisible = false;
  483. }
  484. private isFlipped(vertex1: DecimationVertex, index2: number, point: Vector3, deletedArray: Array<boolean>, borderFactor: number, delTr: Array<DecimationTriangle>): boolean {
  485. for (var i = 0; i < vertex1.triangleCount; ++i) {
  486. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  487. if (t.deleted) continue;
  488. var s = this.references[vertex1.triangleStart + i].vertexId;
  489. var id1 = t.vertices[(s + 1) % 3];
  490. var id2 = t.vertices[(s + 2) % 3];
  491. if ((id1 === index2 || id2 === index2)/* && !this.isTriangleOnBoundingBox(t)*/) {
  492. deletedArray[i] = true;
  493. delTr.push(t);
  494. continue;
  495. }
  496. var d1 = this.vertices[id1].position.subtract(point);
  497. d1 = d1.normalize();
  498. var d2 = this.vertices[id2].position.subtract(point);
  499. d2 = d2.normalize();
  500. if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) return true;
  501. var normal = Vector3.Cross(d1, d2).normalize();
  502. deletedArray[i] = false;
  503. if (Vector3.Dot(normal, t.normal) < 0.2) return true;
  504. }
  505. return false;
  506. }
  507. private updateTriangles(vertexId: number, vertex: DecimationVertex, deletedArray: Array<boolean>, deletedTriangles: number): number {
  508. var newDeleted = deletedTriangles;
  509. for (var i = 0; i < vertex.triangleCount; ++i) {
  510. var ref = this.references[vertex.triangleStart + i];
  511. var t = this.triangles[ref.triangleId];
  512. if (t.deleted) continue;
  513. if (deletedArray[i] && t.deletePending) {
  514. t.deleted = true;
  515. newDeleted++;
  516. continue;
  517. }
  518. t.vertices[ref.vertexId] = vertexId;
  519. t.isDirty = true;
  520. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  521. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  522. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  523. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  524. this.references.push(ref);
  525. }
  526. return newDeleted;
  527. }
  528. private identifyBorder() {
  529. for (var i = 0; i < this.vertices.length; ++i) {
  530. var vCount: Array<number> = [];
  531. var vId: Array<number> = [];
  532. var v = this.vertices[i];
  533. var j: number;
  534. for (j = 0; j < v.triangleCount; ++j) {
  535. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  536. for (var ii = 0; ii < 3; ii++) {
  537. var ofs = 0;
  538. var id = triangle.vertices[ii];
  539. while (ofs < vCount.length) {
  540. if (vId[ofs] === id) break;
  541. ++ofs;
  542. }
  543. if (ofs === vCount.length) {
  544. vCount.push(1);
  545. vId.push(id);
  546. } else {
  547. vCount[ofs]++;
  548. }
  549. }
  550. }
  551. for (j = 0; j < vCount.length; ++j) {
  552. if (vCount[j] === 1) {
  553. this.vertices[vId[j]].isBorder = true;
  554. } else {
  555. this.vertices[vId[j]].isBorder = false;
  556. }
  557. }
  558. }
  559. }
  560. private updateMesh(identifyBorders: boolean = false) {
  561. var i: number;
  562. if (!identifyBorders) {
  563. var newTrianglesVector: Array<DecimationTriangle> = [];
  564. for (i = 0; i < this.triangles.length; ++i) {
  565. if (!this.triangles[i].deleted) {
  566. newTrianglesVector.push(this.triangles[i]);
  567. }
  568. }
  569. this.triangles = newTrianglesVector;
  570. }
  571. for (i = 0; i < this.vertices.length; ++i) {
  572. this.vertices[i].triangleCount = 0;
  573. this.vertices[i].triangleStart = 0;
  574. }
  575. var t: DecimationTriangle;
  576. var j: number;
  577. var v: DecimationVertex;
  578. for (i = 0; i < this.triangles.length; ++i) {
  579. t = this.triangles[i];
  580. for (j = 0; j < 3; ++j) {
  581. v = this.vertices[t.vertices[j]];
  582. v.triangleCount++;
  583. }
  584. }
  585. var tStart = 0;
  586. for (i = 0; i < this.vertices.length; ++i) {
  587. this.vertices[i].triangleStart = tStart;
  588. tStart += this.vertices[i].triangleCount;
  589. this.vertices[i].triangleCount = 0;
  590. }
  591. var newReferences: Array<Reference> = new Array(this.triangles.length * 3);
  592. for (i = 0; i < this.triangles.length; ++i) {
  593. t = this.triangles[i];
  594. for (j = 0; j < 3; ++j) {
  595. v = this.vertices[t.vertices[j]];
  596. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  597. v.triangleCount++;
  598. }
  599. }
  600. this.references = newReferences;
  601. if (identifyBorders) {
  602. this.identifyBorder();
  603. }
  604. }
  605. private vertexError(q: QuadraticMatrix, point: Vector3): number {
  606. var x = point.x;
  607. var y = point.y;
  608. var z = point.z;
  609. 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
  610. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  611. }
  612. private calculateError(vertex1: DecimationVertex, vertex2: DecimationVertex, pointResult?: Vector3, normalResult?: Vector3, uvResult?: Vector2, colorResult?: Color4): number {
  613. var q = vertex1.q.add(vertex2.q);
  614. var border = vertex1.isBorder && vertex2.isBorder;
  615. var error: number = 0;
  616. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  617. if (qDet !== 0 && !border) {
  618. if (!pointResult) {
  619. pointResult = Vector3.Zero();
  620. }
  621. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  622. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  623. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  624. error = this.vertexError(q, pointResult);
  625. //TODO this should be correctly calculated
  626. if (normalResult) {
  627. normalResult.copyFrom(vertex1.normal);
  628. if (vertex1.uv)
  629. uvResult.copyFrom(vertex1.uv);
  630. else if (vertex1.color)
  631. colorResult.copyFrom(vertex1.color);
  632. }
  633. } else {
  634. var p3 = (vertex1.position.add(vertex2.position)).divide(new Vector3(2, 2, 2));
  635. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  636. var error1 = this.vertexError(q, vertex1.position);
  637. var error2 = this.vertexError(q, vertex2.position);
  638. var error3 = this.vertexError(q, p3);
  639. error = Math.min(error1, error2, error3);
  640. if (error === error1) {
  641. if (pointResult) {
  642. pointResult.copyFrom(vertex1.position);
  643. normalResult.copyFrom(vertex1.normal);
  644. if (vertex1.uv)
  645. uvResult.copyFrom(vertex1.uv);
  646. else if (vertex1.color)
  647. colorResult.copyFrom(vertex1.color);
  648. }
  649. } else if (error === error2) {
  650. if (pointResult) {
  651. pointResult.copyFrom(vertex2.position);
  652. normalResult.copyFrom(vertex2.normal);
  653. if (vertex2.uv)
  654. uvResult.copyFrom(vertex2.uv);
  655. else if (vertex2.color)
  656. colorResult.copyFrom(vertex2.color);
  657. }
  658. } else {
  659. if (pointResult) {
  660. pointResult.copyFrom(p3);
  661. normalResult.copyFrom(vertex1.normal);
  662. if (vertex1.uv)
  663. uvResult.copyFrom(vertex1.uv);
  664. else if (vertex1.color)
  665. colorResult.copyFrom(vertex1.color);
  666. }
  667. }
  668. }
  669. return error;
  670. }
  671. }
  672. }