babylon.meshSimplification.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. /**
  28. * The implemented types of simplification.
  29. * At the moment only Quadratic Error Decimation is implemented.
  30. */
  31. export enum SimplificationType {
  32. QUADRATIC
  33. }
  34. export class DecimationTriangle {
  35. public normal: Vector3;
  36. public error: Array<number>;
  37. public deleted: boolean;
  38. public isDirty: boolean;
  39. public borderFactor: number;
  40. constructor(public vertices: Array<number>) {
  41. this.error = new Array<number>(4);
  42. this.deleted = false;
  43. this.isDirty = false;
  44. this.borderFactor = 0;
  45. }
  46. }
  47. export class DecimationVertex {
  48. public q: QuadraticMatrix;
  49. public isBorder: boolean;
  50. public triangleStart: number;
  51. public triangleCount: number;
  52. constructor(public position: Vector3, public normal: Vector3, public uv: Vector2, public id) {
  53. this.isBorder = true;
  54. this.q = new QuadraticMatrix();
  55. this.triangleCount = 0;
  56. this.triangleStart = 0;
  57. }
  58. }
  59. export class QuadraticMatrix {
  60. public data: Array<number>;
  61. constructor(data?: Array<number>) {
  62. this.data = new Array(10);
  63. for (var i = 0; i < 10; ++i) {
  64. if (data && data[i]) {
  65. this.data[i] = data[i];
  66. } else {
  67. this.data[i] = 0;
  68. }
  69. }
  70. }
  71. public det(a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  72. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  73. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  75. return det;
  76. }
  77. public addInPlace(matrix: QuadraticMatrix) {
  78. for (var i = 0; i < 10; ++i) {
  79. this.data[i] += matrix.data[i];
  80. }
  81. }
  82. public addArrayInPlace(data: Array<number>) {
  83. for (var i = 0; i < 10; ++i) {
  84. this.data[i] += data[i];
  85. }
  86. }
  87. public add(matrix: QuadraticMatrix): QuadraticMatrix {
  88. var m = new QuadraticMatrix();
  89. for (var i = 0; i < 10; ++i) {
  90. m.data[i] = this.data[i] + matrix.data[i];
  91. }
  92. return m;
  93. }
  94. public static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix {
  95. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  96. }
  97. //returning an array to avoid garbage collection
  98. public static DataFromNumbers(a: number, b: number, c: number, d: number) {
  99. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  100. }
  101. }
  102. export class Reference {
  103. constructor(public vertexId: number, public triangleId: number) { }
  104. }
  105. /**
  106. * An implementation of the Quadratic Error simplification algorithm.
  107. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  108. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  109. * @author RaananW
  110. */
  111. export class QuadraticErrorSimplification implements ISimplifier {
  112. private triangles: Array<DecimationTriangle>;
  113. private vertices: Array<DecimationVertex>;
  114. private references: Array<Reference>;
  115. private initialised: boolean = false;
  116. public syncIterations = 5000;
  117. public agressiveness: number;
  118. public decimationIterations: number;
  119. constructor(private _mesh: Mesh) {
  120. this.agressiveness = 7;
  121. this.decimationIterations = 100;
  122. }
  123. public simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void) {
  124. this.initWithMesh(this._mesh, () => {
  125. this.runDecimation(settings, successCallback);
  126. });
  127. }
  128. private runDecimation(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void) {
  129. var targetCount = ~~(this.triangles.length * settings.quality);
  130. var deletedTriangles = 0;
  131. var triangleCount = this.triangles.length;
  132. var iterationFunction = (iteration: number, callback) => {
  133. setTimeout(() => {
  134. if (iteration % 5 === 0) {
  135. this.updateMesh(iteration === 0);
  136. }
  137. for (var i = 0; i < this.triangles.length; ++i) {
  138. this.triangles[i].isDirty = false;
  139. }
  140. var threshold = 0.000000001 * Math.pow((iteration + 3), this.agressiveness);
  141. var trianglesIterator = (i) => {
  142. var t = this.triangles[i];
  143. if (!t) return;
  144. if (t.error[3] > threshold) { return }
  145. if (t.deleted) { return }
  146. if (t.isDirty) { return }
  147. for (var j = 0; j < 3; ++j) {
  148. if (t.error[j] < threshold) {
  149. var deleted0: Array<boolean> = [];
  150. var deleted1: Array<boolean> = [];
  151. var i0 = t.vertices[j];
  152. var i1 = t.vertices[(j + 1) % 3];
  153. var v0 = this.vertices[i0];
  154. var v1 = this.vertices[i1];
  155. if (v0.isBorder !== v1.isBorder) continue;
  156. var p = Vector3.Zero();
  157. var n = Vector3.Zero();
  158. var uv = Vector2.Zero();
  159. this.calculateError(v0, v1, p, n, uv);
  160. if (this.isFlipped(v0, i1, p, deleted0, t.borderFactor)) continue;
  161. if (this.isFlipped(v1, i0, p, deleted1, t.borderFactor)) continue;
  162. v0.position = p;
  163. v0.normal = n;
  164. v0.uv = uv;
  165. v0.q = v1.q.add(v0.q);
  166. var tStart = this.references.length;
  167. deletedTriangles = this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  168. deletedTriangles = this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  169. var tCount = this.references.length - tStart;
  170. if (tCount <= v0.triangleCount) {
  171. if (tCount) {
  172. for (var c = 0; c < tCount; c++) {
  173. this.references[v0.triangleStart + c] = this.references[tStart + c];
  174. }
  175. }
  176. } else {
  177. v0.triangleStart = tStart;
  178. }
  179. v0.triangleCount = tCount;
  180. break;
  181. }
  182. }
  183. };
  184. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback, () => { return (triangleCount - deletedTriangles <= targetCount) });
  185. }, 0);
  186. };
  187. AsyncLoop.Run(this.decimationIterations, (loop: AsyncLoop) => {
  188. if (triangleCount - deletedTriangles <= targetCount) loop.breakLoop();
  189. else {
  190. iterationFunction(loop.index, () => {
  191. loop.executeNext();
  192. });
  193. }
  194. }, () => {
  195. setTimeout(() => {
  196. successCallback(this.reconstructMesh());
  197. }, 0);
  198. });
  199. }
  200. private initWithMesh(mesh: Mesh, callback: Function) {
  201. if (!mesh) return;
  202. this.vertices = [];
  203. this.triangles = [];
  204. this._mesh = mesh;
  205. var positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);
  206. var normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);
  207. var uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);
  208. var indices = mesh.getIndices();
  209. var vertexInit = (i) => {
  210. var vertex = new DecimationVertex(Vector3.FromArray(positionData, i * 3), Vector3.FromArray(normalData, i * 3), Vector2.FromArray(uvs, i * 2), i);
  211. this.vertices.push(vertex);
  212. };
  213. var totalVertices = mesh.getTotalVertices();
  214. AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, () => {
  215. var indicesInit = (i) => {
  216. var pos = i * 3;
  217. var i0 = indices[pos + 0];
  218. var i1 = indices[pos + 1];
  219. var i2 = indices[pos + 2];
  220. var triangle = new DecimationTriangle([this.vertices[i0].id, this.vertices[i1].id, this.vertices[i2].id]);
  221. this.triangles.push(triangle);
  222. };
  223. AsyncLoop.SyncAsyncForLoop(indices.length / 3, this.syncIterations, indicesInit, () => {
  224. this.init(callback);
  225. });
  226. });
  227. }
  228. private init(callback: Function) {
  229. var triangleInit1 = (i) => {
  230. var t = this.triangles[i];
  231. 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();
  232. for (var j = 0; j < 3; j++) {
  233. 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))));
  234. }
  235. };
  236. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, () => {
  237. var triangleInit2 = (i) => {
  238. var t = this.triangles[i];
  239. for (var j = 0; j < 3; ++j) {
  240. t.error[j] = this.calculateError(this.vertices[t.vertices[j]], this.vertices[t.vertices[(j + 1) % 3]]);
  241. }
  242. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  243. };
  244. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2, () => {
  245. this.initialised = true;
  246. callback();
  247. });
  248. });
  249. }
  250. private reconstructMesh(): Mesh {
  251. var newTriangles: Array<DecimationTriangle> = [];
  252. var i: number;
  253. for (i = 0; i < this.vertices.length; ++i) {
  254. this.vertices[i].triangleCount = 0;
  255. }
  256. var t: DecimationTriangle;
  257. var j: number;
  258. for (i = 0; i < this.triangles.length; ++i) {
  259. if (!this.triangles[i].deleted) {
  260. t = this.triangles[i];
  261. for (j = 0; j < 3; ++j) {
  262. this.vertices[t.vertices[j]].triangleCount = 1;
  263. }
  264. newTriangles.push(t);
  265. }
  266. }
  267. var newVerticesOrder = [];
  268. //compact vertices, get the IDs of the vertices used.
  269. var dst = 0;
  270. for (i = 0; i < this.vertices.length; ++i) {
  271. if (this.vertices[i].triangleCount) {
  272. this.vertices[i].triangleStart = dst;
  273. this.vertices[dst].position = this.vertices[i].position;
  274. this.vertices[dst].normal = this.vertices[i].normal;
  275. this.vertices[dst].uv = this.vertices[i].uv;
  276. newVerticesOrder.push(i);
  277. dst++;
  278. }
  279. }
  280. for (i = 0; i < newTriangles.length; ++i) {
  281. t = newTriangles[i];
  282. for (j = 0; j < 3; ++j) {
  283. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  284. }
  285. }
  286. this.vertices = this.vertices.slice(0, dst);
  287. var newPositionData = [];
  288. var newNormalData = [];
  289. var newUVsData = [];
  290. for (i = 0; i < newVerticesOrder.length; ++i) {
  291. newPositionData.push(this.vertices[i].position.x);
  292. newPositionData.push(this.vertices[i].position.y);
  293. newPositionData.push(this.vertices[i].position.z);
  294. newNormalData.push(this.vertices[i].normal.x);
  295. newNormalData.push(this.vertices[i].normal.y);
  296. newNormalData.push(this.vertices[i].normal.z);
  297. newUVsData.push(this.vertices[i].uv.x);
  298. newUVsData.push(this.vertices[i].uv.y);
  299. }
  300. var newIndicesArray: Array<number> = [];
  301. for (i = 0; i < newTriangles.length; ++i) {
  302. newIndicesArray.push(newTriangles[i].vertices[0]);
  303. newIndicesArray.push(newTriangles[i].vertices[1]);
  304. newIndicesArray.push(newTriangles[i].vertices[2]);
  305. }
  306. var newMesh = new Mesh(this._mesh + "Decimated", this._mesh.getScene());
  307. newMesh.material = this._mesh.material;
  308. newMesh.parent = this._mesh.parent;
  309. newMesh.setIndices(newIndicesArray);
  310. newMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);
  311. newMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);
  312. newMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);
  313. //preparing the skeleton support
  314. if (this._mesh.skeleton) {
  315. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  316. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  317. }
  318. return newMesh;
  319. }
  320. private isFlipped(vertex1: DecimationVertex, index2: number, point: Vector3, deletedArray: Array<boolean>, borderFactor: number): boolean {
  321. for (var i = 0; i < vertex1.triangleCount; ++i) {
  322. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  323. if (t.deleted) continue;
  324. var s = this.references[vertex1.triangleStart + i].vertexId;
  325. var id1 = t.vertices[(s + 1) % 3];
  326. var id2 = t.vertices[(s + 2) % 3];
  327. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  328. deletedArray[i] = true;
  329. continue;
  330. }
  331. var d1 = this.vertices[id1].position.subtract(point);
  332. d1 = d1.normalize();
  333. var d2 = this.vertices[id2].position.subtract(point);
  334. d2 = d2.normalize();
  335. if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) return true;
  336. var normal = Vector3.Cross(d1, d2).normalize();
  337. deletedArray[i] = false;
  338. if (Vector3.Dot(normal, t.normal) < 0.2) return true;
  339. }
  340. return false;
  341. }
  342. private updateTriangles(vertexId: number, vertex: DecimationVertex, deletedArray: Array<boolean>, deletedTriangles: number): number {
  343. var newDeleted = deletedTriangles;
  344. for (var i = 0; i < vertex.triangleCount; ++i) {
  345. var ref = this.references[vertex.triangleStart + i];
  346. var t = this.triangles[ref.triangleId];
  347. if (t.deleted) continue;
  348. if (deletedArray[i]) {
  349. t.deleted = true;
  350. newDeleted++;
  351. continue;
  352. }
  353. t.vertices[ref.vertexId] = vertexId;
  354. t.isDirty = true;
  355. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  356. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  357. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  358. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  359. this.references.push(ref);
  360. }
  361. return newDeleted;
  362. }
  363. private identifyBorder() {
  364. for (var i = 0; i < this.vertices.length; ++i) {
  365. var vCount: Array<number> = [];
  366. var vId: Array<number> = [];
  367. var v = this.vertices[i];
  368. var j: number;
  369. for (j = 0; j < v.triangleCount; ++j) {
  370. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  371. for (var ii = 0; ii < 3; ii++) {
  372. var ofs = 0;
  373. var id = triangle.vertices[ii];
  374. while (ofs < vCount.length) {
  375. if (vId[ofs] === id) break;
  376. ++ofs;
  377. }
  378. if (ofs === vCount.length) {
  379. vCount.push(1);
  380. vId.push(id);
  381. } else {
  382. vCount[ofs]++;
  383. }
  384. }
  385. }
  386. for (j = 0; j < vCount.length; ++j) {
  387. if (vCount[j] === 1) {
  388. this.vertices[vId[j]].isBorder = true;
  389. } else {
  390. this.vertices[vId[j]].isBorder = false;
  391. }
  392. }
  393. }
  394. }
  395. private updateMesh(identifyBorders: boolean = false) {
  396. var i: number;
  397. if (!identifyBorders) {
  398. var newTrianglesVector: Array<DecimationTriangle> = [];
  399. for (i = 0; i < this.triangles.length; ++i) {
  400. if (!this.triangles[i].deleted) {
  401. newTrianglesVector.push(this.triangles[i]);
  402. }
  403. }
  404. this.triangles = newTrianglesVector;
  405. }
  406. for (i = 0; i < this.vertices.length; ++i) {
  407. this.vertices[i].triangleCount = 0;
  408. this.vertices[i].triangleStart = 0;
  409. }
  410. var t: DecimationTriangle;
  411. var j: number;
  412. var v: DecimationVertex;
  413. for (i = 0; i < this.triangles.length; ++i) {
  414. t = this.triangles[i];
  415. for (j = 0; j < 3; ++j) {
  416. v = this.vertices[t.vertices[j]];
  417. v.triangleCount++;
  418. }
  419. }
  420. var tStart = 0;
  421. for (i = 0; i < this.vertices.length; ++i) {
  422. this.vertices[i].triangleStart = tStart;
  423. tStart += this.vertices[i].triangleCount;
  424. this.vertices[i].triangleCount = 0;
  425. }
  426. var newReferences: Array<Reference> = new Array(this.triangles.length * 3);
  427. for (i = 0; i < this.triangles.length; ++i) {
  428. t = this.triangles[i];
  429. for (j = 0; j < 3; ++j) {
  430. v = this.vertices[t.vertices[j]];
  431. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  432. v.triangleCount++;
  433. }
  434. }
  435. this.references = newReferences;
  436. if (identifyBorders) {
  437. this.identifyBorder();
  438. }
  439. }
  440. private vertexError(q: QuadraticMatrix, point: Vector3): number {
  441. var x = point.x;
  442. var y = point.y;
  443. var z = point.z;
  444. 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
  445. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  446. }
  447. private calculateError(vertex1: DecimationVertex, vertex2: DecimationVertex, pointResult?: Vector3, normalResult?: Vector3, uvResult?: Vector2): number {
  448. var q = vertex1.q.add(vertex2.q);
  449. var border = vertex1.isBorder && vertex2.isBorder;
  450. var error: number = 0;
  451. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  452. if (qDet !== 0 && !border) {
  453. if (!pointResult) {
  454. pointResult = Vector3.Zero();
  455. }
  456. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  457. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  458. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  459. error = this.vertexError(q, pointResult);
  460. //TODO this should be correctly calculated
  461. if (normalResult) {
  462. normalResult.copyFrom(vertex1.normal);
  463. uvResult.copyFrom(vertex1.uv);
  464. }
  465. } else {
  466. var p3 = (vertex1.position.add(vertex2.position)).divide(new Vector3(2, 2, 2));
  467. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  468. var error1 = this.vertexError(q, vertex1.position);
  469. var error2 = this.vertexError(q, vertex2.position);
  470. var error3 = this.vertexError(q, p3);
  471. error = Math.min(error1, error2, error3);
  472. if (error === error1) {
  473. if (pointResult) {
  474. pointResult.copyFrom(vertex1.position);
  475. normalResult.copyFrom(vertex1.normal);
  476. uvResult.copyFrom(vertex1.uv);
  477. }
  478. } else if (error === error2) {
  479. if (pointResult) {
  480. pointResult.copyFrom(vertex2.position);
  481. normalResult.copyFrom(vertex2.normal);
  482. uvResult.copyFrom(vertex2.uv);
  483. }
  484. } else {
  485. if (pointResult) {
  486. pointResult.copyFrom(p3);
  487. normalResult.copyFrom(norm3);
  488. uvResult.copyFrom(vertex1.uv);
  489. }
  490. }
  491. }
  492. return error;
  493. }
  494. }
  495. }