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: BABYLON.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: BABYLON.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: BABYLON.Vector3, public normal: BABYLON.Vector3, public uv: BABYLON.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: BABYLON.Mesh) {
  120. this.agressiveness = 7;
  121. this.decimationIterations = 100;
  122. }
  123. public simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: BABYLON.Mesh) => void) {
  124. this.initWithMesh(this._mesh, () => {
  125. this.runDecimation(settings, successCallback);
  126. });
  127. }
  128. private runDecimation(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: BABYLON.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 tIdx = ((this.triangles.length / 2) + i) % this.triangles.length;
  143. var t = this.triangles[i];
  144. if (!t) return;
  145. if (t.error[3] > threshold) { return }
  146. if (t.deleted) { return }
  147. if (t.isDirty) { return }
  148. for (var j = 0; j < 3; ++j) {
  149. if (t.error[j] < threshold) {
  150. var deleted0: Array<boolean> = [];
  151. var deleted1: Array<boolean> = [];
  152. var i0 = t.vertices[j];
  153. var i1 = t.vertices[(j + 1) % 3];
  154. var v0 = this.vertices[i0];
  155. var v1 = this.vertices[i1];
  156. if (v0.isBorder != v1.isBorder) continue;
  157. var p = BABYLON.Vector3.Zero();
  158. var n = BABYLON.Vector3.Zero();
  159. var uv = BABYLON.Vector2.Zero();
  160. this.calculateError(v0, v1, p, n, uv);
  161. if (this.isFlipped(v0, i1, p, deleted0, t.borderFactor)) continue;
  162. if (this.isFlipped(v1, i0, p, deleted1, t.borderFactor)) continue;
  163. v0.position = p;
  164. v0.normal = n;
  165. v0.uv = uv;
  166. v0.q = v1.q.add(v0.q);
  167. var tStart = this.references.length;
  168. deletedTriangles = this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  169. deletedTriangles = this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  170. var tCount = this.references.length - tStart;
  171. if (tCount <= v0.triangleCount) {
  172. if (tCount) {
  173. for (var c = 0; c < tCount; c++) {
  174. this.references[v0.triangleStart + c] = this.references[tStart + c];
  175. }
  176. }
  177. } else {
  178. v0.triangleStart = tStart;
  179. }
  180. v0.triangleCount = tCount;
  181. break;
  182. }
  183. }
  184. }
  185. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, trianglesIterator, callback, () => { return (triangleCount - deletedTriangles <= targetCount) })
  186. }, 0);
  187. }
  188. new AsyncLoop(this.decimationIterations, (loop: AsyncLoop) => {
  189. if (triangleCount - deletedTriangles <= targetCount) loop.breakLoop();
  190. else {
  191. iterationFunction(loop.index, () => {
  192. loop.executeNext();
  193. });
  194. }
  195. }, () => {
  196. setTimeout(() => {
  197. successCallback(this.reconstructMesh());
  198. }, 0);
  199. });
  200. }
  201. private initWithMesh(mesh: BABYLON.Mesh, callback: Function) {
  202. if (!mesh) return;
  203. this.vertices = [];
  204. this.triangles = [];
  205. this._mesh = mesh;
  206. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  207. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  208. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  209. var indices = mesh.getIndices();
  210. var vertexInit = (i) => {
  211. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  212. this.vertices.push(vertex);
  213. }
  214. var totalVertices = mesh.getTotalVertices();
  215. AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, () => {
  216. var indicesInit = (i) => {
  217. var pos = i * 3;
  218. var i0 = indices[pos + 0];
  219. var i1 = indices[pos + 1];
  220. var i2 = indices[pos + 2];
  221. var triangle = new DecimationTriangle([this.vertices[i0].id, this.vertices[i1].id, this.vertices[i2].id]);
  222. this.triangles.push(triangle);
  223. }
  224. AsyncLoop.SyncAsyncForLoop(indices.length / 3, this.syncIterations, indicesInit, () => {
  225. this.init(callback);
  226. });
  227. })
  228. }
  229. private init(callback: Function) {
  230. var triangleInit1 = (i) => {
  231. var t = this.triangles[i];
  232. t.normal = BABYLON.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();
  233. for (var j = 0; j < 3; j++) {
  234. this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, this.vertices[t.vertices[0]].position))));
  235. }
  236. }
  237. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, () => {
  238. var triangleInit2 = (i) => {
  239. var t = this.triangles[i];
  240. for (var j = 0; j < 3; ++j) {
  241. t.error[j] = this.calculateError(this.vertices[t.vertices[j]], this.vertices[t.vertices[(j + 1) % 3]]);
  242. }
  243. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  244. }
  245. AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit2, () => {
  246. this.initialised = true;
  247. callback()
  248. });
  249. });
  250. }
  251. private reconstructMesh(): BABYLON.Mesh {
  252. var newTriangles: Array<DecimationTriangle> = [];
  253. for (var i = 0; i < this.vertices.length; ++i) {
  254. this.vertices[i].triangleCount = 0;
  255. }
  256. for (var i = 0; i < this.triangles.length; ++i) {
  257. if (!this.triangles[i].deleted) {
  258. var t = this.triangles[i];
  259. for (var j = 0; j < 3; ++j) {
  260. this.vertices[t.vertices[j]].triangleCount = 1;
  261. }
  262. newTriangles.push(t);
  263. }
  264. }
  265. var newVerticesOrder = [];
  266. //compact vertices, get the IDs of the vertices used.
  267. var dst = 0;
  268. for (var i = 0; i < this.vertices.length; ++i) {
  269. if (this.vertices[i].triangleCount) {
  270. this.vertices[i].triangleStart = dst;
  271. this.vertices[dst].position = this.vertices[i].position;
  272. this.vertices[dst].normal = this.vertices[i].normal;
  273. this.vertices[dst].uv = this.vertices[i].uv;
  274. newVerticesOrder.push(i);
  275. dst++;
  276. }
  277. }
  278. for (var i = 0; i < newTriangles.length; ++i) {
  279. var t = newTriangles[i];
  280. for (var j = 0; j < 3; ++j) {
  281. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  282. }
  283. }
  284. this.vertices = this.vertices.slice(0, dst);
  285. var newPositionData = [];
  286. var newNormalData = [];
  287. var newUVsData = [];
  288. for (var i = 0; i < newVerticesOrder.length; ++i) {
  289. newPositionData.push(this.vertices[i].position.x);
  290. newPositionData.push(this.vertices[i].position.y);
  291. newPositionData.push(this.vertices[i].position.z);
  292. newNormalData.push(this.vertices[i].normal.x);
  293. newNormalData.push(this.vertices[i].normal.y);
  294. newNormalData.push(this.vertices[i].normal.z);
  295. newUVsData.push(this.vertices[i].uv.x);
  296. newUVsData.push(this.vertices[i].uv.y);
  297. }
  298. var newIndicesArray: Array<number> = [];
  299. for (var i = 0; i < newTriangles.length; ++i) {
  300. newIndicesArray.push(newTriangles[i].vertices[0]);
  301. newIndicesArray.push(newTriangles[i].vertices[1]);
  302. newIndicesArray.push(newTriangles[i].vertices[2]);
  303. }
  304. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  305. newMesh.material = this._mesh.material;
  306. newMesh.parent = this._mesh.parent;
  307. newMesh.setIndices(newIndicesArray);
  308. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  309. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  310. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  311. //preparing the skeleton support
  312. if (this._mesh.skeleton) {
  313. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  314. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  315. }
  316. return newMesh;
  317. }
  318. private isFlipped(vertex1: DecimationVertex, index2: number, point: BABYLON.Vector3, deletedArray: Array<boolean>, borderFactor: number): boolean {
  319. for (var i = 0; i < vertex1.triangleCount; ++i) {
  320. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  321. if (t.deleted) continue;
  322. var s = this.references[vertex1.triangleStart + i].vertexId;
  323. var id1 = t.vertices[(s + 1) % 3];
  324. var id2 = t.vertices[(s + 2) % 3];
  325. if ((id1 == index2 || id2 == index2) && borderFactor < 2) {
  326. deletedArray[i] = true;
  327. continue;
  328. }
  329. var d1 = this.vertices[id1].position.subtract(point);
  330. d1 = d1.normalize();
  331. var d2 = this.vertices[id2].position.subtract(point);
  332. d2 = d2.normalize();
  333. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) return true;
  334. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  335. deletedArray[i] = false;
  336. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) return true;
  337. }
  338. return false;
  339. }
  340. private updateTriangles(vertexId: number, vertex: DecimationVertex, deletedArray: Array<boolean>, deletedTriangles: number): number {
  341. var newDeleted = deletedTriangles;
  342. for (var i = 0; i < vertex.triangleCount; ++i) {
  343. var ref = this.references[vertex.triangleStart + i];
  344. var t = this.triangles[ref.triangleId];
  345. if (t.deleted) continue;
  346. if (deletedArray[i]) {
  347. t.deleted = true;
  348. newDeleted++;
  349. continue;
  350. }
  351. t.vertices[ref.vertexId] = vertexId;
  352. t.isDirty = true;
  353. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  354. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  355. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  356. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  357. this.references.push(ref);
  358. }
  359. return newDeleted;
  360. }
  361. private identifyBorder() {
  362. for (var i = 0; i < this.vertices.length; ++i) {
  363. var vCount: Array<number> = [];
  364. var vId: Array<number> = [];
  365. var v = this.vertices[i];
  366. for (var j = 0; j < v.triangleCount; ++j) {
  367. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  368. for (var ii = 0; ii < 3; ii++) {
  369. var ofs = 0;
  370. var id = triangle.vertices[ii];
  371. while (ofs < vCount.length) {
  372. if (vId[ofs] === id) break;
  373. ++ofs;
  374. }
  375. if (ofs == vCount.length) {
  376. vCount.push(1);
  377. vId.push(id);
  378. } else {
  379. vCount[ofs]++;
  380. }
  381. }
  382. }
  383. for (var j = 0; j < vCount.length; ++j) {
  384. if (vCount[j] == 1) {
  385. this.vertices[vId[j]].isBorder = true;
  386. } else {
  387. this.vertices[vId[j]].isBorder = false;
  388. }
  389. }
  390. }
  391. }
  392. private updateMesh(identifyBorders: boolean = false) {
  393. if (!identifyBorders) {
  394. var dst = 0;
  395. var newTrianglesVector: Array<DecimationTriangle> = [];
  396. for (var i = 0; i < this.triangles.length; ++i) {
  397. if (!this.triangles[i].deleted) {
  398. newTrianglesVector.push(this.triangles[i]);
  399. }
  400. }
  401. this.triangles = newTrianglesVector;
  402. }
  403. for (var i = 0; i < this.vertices.length; ++i) {
  404. this.vertices[i].triangleCount = 0;
  405. this.vertices[i].triangleStart = 0;
  406. }
  407. for (var i = 0; i < this.triangles.length; ++i) {
  408. var t = this.triangles[i];
  409. for (var j = 0; j < 3; ++j) {
  410. var v = this.vertices[t.vertices[j]];
  411. v.triangleCount++;
  412. }
  413. }
  414. var tStart = 0;
  415. for (var i = 0; i < this.vertices.length; ++i) {
  416. this.vertices[i].triangleStart = tStart;
  417. tStart += this.vertices[i].triangleCount;
  418. this.vertices[i].triangleCount = 0;
  419. }
  420. var newReferences: Array<Reference> = new Array(this.triangles.length * 3);
  421. for (var i = 0; i < this.triangles.length; ++i) {
  422. var t = this.triangles[i];
  423. for (var j = 0; j < 3; ++j) {
  424. var v = this.vertices[t.vertices[j]];
  425. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  426. v.triangleCount++;
  427. }
  428. }
  429. this.references = newReferences;
  430. if (identifyBorders) {
  431. this.identifyBorder();
  432. }
  433. }
  434. private vertexError(q: QuadraticMatrix, point: BABYLON.Vector3): number {
  435. var x = point.x;
  436. var y = point.y;
  437. var z = point.z;
  438. 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
  439. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  440. }
  441. private calculateError(vertex1: DecimationVertex, vertex2: DecimationVertex, pointResult?: BABYLON.Vector3, normalResult?: BABYLON.Vector3, uvResult?: BABYLON.Vector2): number {
  442. var q = vertex1.q.add(vertex2.q);
  443. var border = vertex1.isBorder && vertex2.isBorder;
  444. var error: number = 0;
  445. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  446. if (qDet != 0 && !border) {
  447. if (!pointResult) {
  448. pointResult = BABYLON.Vector3.Zero();
  449. }
  450. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  451. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  452. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  453. error = this.vertexError(q, pointResult);
  454. //TODO this should be correctly calculated
  455. if (normalResult) {
  456. normalResult.copyFrom(vertex1.normal);
  457. uvResult.copyFrom(vertex1.uv);
  458. }
  459. } else {
  460. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  461. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  462. var error1 = this.vertexError(q, vertex1.position);
  463. var error2 = this.vertexError(q, vertex2.position);
  464. var error3 = this.vertexError(q, p3);
  465. error = Math.min(error1, error2, error3);
  466. if (error === error1) {
  467. if (pointResult) {
  468. pointResult.copyFrom(vertex1.position);
  469. normalResult.copyFrom(vertex1.normal);
  470. uvResult.copyFrom(vertex1.uv);
  471. }
  472. } else if (error === error2) {
  473. if (pointResult) {
  474. pointResult.copyFrom(vertex2.position);
  475. normalResult.copyFrom(vertex2.normal);
  476. uvResult.copyFrom(vertex2.uv);
  477. }
  478. } else {
  479. if (pointResult) {
  480. pointResult.copyFrom(p3);
  481. normalResult.copyFrom(norm3);
  482. uvResult.copyFrom(vertex1.uv);
  483. }
  484. }
  485. }
  486. return error;
  487. }
  488. }
  489. }